需求:
生成一个数组,数组内包含n个随机的RGB颜色值。
1、先定义一个函数,用于生成一个随机的RGB颜色值。
function generateRandomColor() {
const randomRed = Math.floor(Math.random() * 256); // 生成一个0到255之间的随机整数,代表红色通道的值。
const randomGreen = Math.floor(Math.random() * 256); // 生成一个0到255之间的随机整数,代表绿色通道的值。
const randomBlue = Math.floor(Math.random() * 256); // 生成一个0到255之间的随机整数,代表蓝色通道的值。
return `rgb(${randomRed}, ${randomGreen}, ${randomBlue})`; // 返回一个字符串,格式为rgb(red, green, blue)
}
2、再定义一个函数,用于生成n个随机的RGB颜色值。
function generateRandomColors(n) {
const colors = [];
for (let i = 0; i < n; i++) { // 循环n次,每次调用generateRandomColor函数生成一个颜色值,并将其添加到colors数组中。
colors.push(generateRandomColor());
}
return colors;
}
3、测试
console.log(generateRandomColors(5));
// 输出结果为:['rgb(107, 56, 173)', 'rgb(129, 94, 106)', 'rgb(239, 221, 219)', 'rgb(44, 83, 17)', 'rgb(149, 157, 76)']