Populating a 2D array in Javascript with random numbers

前端 未结 3 1069
日久生厌
日久生厌 2021-01-27 11:15

I\'m trying to populate a 2D array in javascript with random numbers. Although each column in the array is random, each row is identical which is not what I want (see image bel

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-27 11:27

    This can be accomplished using a combination of Array.prototype.fill() and Array.prototype.map():

    new Array(rows).fill([]).map(x => Array(columns).fill(0).map(x => x + Math.floor(Math.random() * (max - min)) + min));
    

    For example, we can create a 100 by 964 column array full of random numbers between 900 and 1000 using the following:

    new Array(100).fill([]).map(x => Array(964).fill(0).map(x => x + Math.floor(Math.random() * (1000 - 900)) + 900));
    

提交回复
热议问题