Creating array of length n with random numbers in JavaScript

后端 未结 6 1702
耶瑟儿~
耶瑟儿~ 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:18

    What does Array#fill do?

    According to MDN

    The fill() method fills all the elements of an array from a start index to an end index with a static value.

    You can use Function#apply, Array#map, Math.floor(), Math.random().

    In ES6, Array#from and Arrow function can be used.

    Array.from({length: 6}, () => Math.floor(Math.random() * 9));
    

    Array.apply(null, Array(6)).map(() => Math.floor(Math.random() * 9));

    var randomArr = Array.from({length: 6}, () => Math.floor(Math.random() * 9));
    
    document.getElementById('result').innerHTML = JSON.stringify(randomArr, 0, 4); // For demo only

    In ES5:

    Array.apply(null, Array(6)).map(function(item, index){
        return Math.floor(Math.random() * 9);
    });
    

    var randomArr = Array.apply(null, Array(6)).map(function(item, index){
        return Math.floor(Math.random() * 9)
    });
    
    document.getElementById('result').innerHTML = JSON.stringify(randomArr, 0, 4);

    What is Array.apply(null, Array(n))? Can new Array(n) used here?

    Both the above code create new array of six elements, each element having value as undefined. However, when used new syntax, the created array is not iterable. To make the array iterable, Array.apply(null, Array(6)) syntax is used.


    If you have lodash included on page, it's really easy.

    _.times(6, _.random.bind(0, 100))
            ^                        - Number of elements in array
                             ^       - Random number range min
                                ^^^  - Random number range max
    

    Note: This answer is inspired from Colin Toh's blog

提交回复
热议问题