const colors = ['red', 'green', 'blue', 'yellow']
let startingIndex = 2
const random = colors[Math.floor(Math.random() * 4)]
console.log(random)
if(startingIndex >= 2) {
randomColor.push(random)
console.log(randomColor)
}
我正在根据startingIndex的数量将绿色/黄色/红色/蓝色中的随机单词推入randomColor数组,该数量可以在2到20之间。例如startingIndex = 4,因此randomColor arr应包含4倍['red','red','yellow','blue']的随机词,并根据startingIndex的长度来更改randomColor arr中的项目数。 谁能阐明如何实现这一目标?
答案 0 :(得分:0)
您将需要循环。例如一个简单的for
循环:
const colors = ['red', 'green', 'blue', 'yellow'];
let startingIndex = 5;
const randomColors = [];
for (let i = 0; i < startingIndex; i++) {
const random = colors[Math.floor(Math.random() * colors.length)]
randomColors.push(random)
}
console.log(randomColors)
注意:最好使用colors.length
而不是硬编码4,因为这样一来,当您决定添加第五种颜色时,代码就可以了。
您可以采用功能更强大的编程风格进行操作:
function getRandomColors(colors, length) {
return Array.from({length}, _ =>
colors[Math.floor(Math.random() * colors.length)]);
}
const randomColors = getRandomColors(['red', 'green', 'blue', 'yellow'], 5)
console.log(randomColors);