首页 > 解决方案 > 用随机数填充 Javascript 中的二维数组

问题描述

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

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

标签: javascriptarraysrandomauto-populating

解决方案


使用地图的一种方法

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

console.log(op)


推荐阅读