繁体   English   中英

根据变量的长度将随机数推入数组

[英]Push random numbers to array based on length of variable

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中的项目数。 任何人都可以阐明如何实现这一目标吗?

您将需要一个循环。 例如一个简单的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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM