简体   繁体   中英

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)
        }

I'm trying to push a random word from green/yellow/red/blue into a randomColor array based off the number of the startingIndex which can be anywhere from 2-20. eg startingIndex = 4 so the randomColor arr should contain random words 4 times ['red','red','yellow','blue'] and changes how many items are in the randomColor arr based on what the length of the startingIndex is. Could anyone shed some light on how this may be achieved?

You would need a loop. For instance a simple for loop:

 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) 

NB: it is better to use colors.length than hard-coded 4, as then the code will be fine when you decide to add a fifth color.

In a more functional programming style you could do:

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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