用随机数填充Javascript中的2D数组

时间:2019-02-04 20:02:27

标签: javascript arrays random auto-populating

我正在尝试使用随机数填充javascript中的2D数组。尽管数组中的每一列都是随机的,但每一行都是相同的,这不是我想要的(请参见下图)。我希望行和列都是随机的。

http://eeldesigns.com/image.jpg

cols = 5;
rows = 10;

front = new Array(cols).fill(new Array(rows));

// Loop through Initial array to randomly place cells
for(var x = 0; x < cols; x++){
  for(var y = 0; y < rows; y++){
    front[x][y] = Math.floor(Math.random()*5);
  }
}
console.table(front) ;

3 个答案:

答案 0 :(得分:2)

使用map

的一种方法

let op = new Array(10)
         .fill(0)
         .map(e=>(new Array(5)
         .fill(0)
         .map(e=> Math.floor(Math.random() * 5))))

console.log(op)

答案 1 :(得分:1)

问题在于您没有初始化该行。很容易解决:

cols = 5;
rows = 10;

front = new Array(cols)// .fill(new Array(rows));

// Loop through Initial array to randomly place cells
for(var x = 0; x < cols; x++){
  front[x] = [];  // ***** Added this line *****
  for(var y = 0; y < rows; y++){
    front[x][y] = Math.floor(Math.random()*5);
  }
}
console.table(front) ; // browser console only, not StackOverflow's

更新

这是一个更干净的版本,与Code Maniac的版本有些相似,但做了一些简化:

const randomTable = (rows, cols) => Array.from(
  {length: rows}, 
  () => Array.from({length: cols}, () => Math.floor(Math.random() * 5))
)

console.table(randomTable(10, 5)) // browser console only, not StackOverflow's

答案 2 :(得分:0)

这可以通过结合使用Array.prototype.fill()Array.prototype.map()来实现:

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

例如,我们可以使用以下方法创建一个100 x 964列的数组,其中包含900到1000之间的随机数:

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