Creating array of length n with random numbers in JavaScript

后端 未结 6 1706
耶瑟儿~
耶瑟儿~ 2020-12-09 03:44

Following up on this answer for creating an array of specified length, I executed the below to get a corresponding result but filled with random numbers, instead of zeros.

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 04:24

    var randoms = Array(4).fill(Math.floor(Math.random() * 9));
    

    This line of code will create a list of 4 of the same number because fill takes a single value and repeats it for the length of the list. What you want to do is run the random number generator each time:

    var makeARandomNumber = function(){
        return Math.floor(Math.random() * 9);
    }
    var randoms = Array(5).fill(0).map(makeARandomNumber);
    console.log(randoms)
    // => [4, 4, 3, 2, 6]
    

    https://jsfiddle.net/t4jtjcde/

提交回复
热议问题