0

我正在尝试用随机数填充 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) ;
4

3 回答 3

2

使用地图的一种方法

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

console.log(op)

于 2019-02-04T20:08:14.587 回答
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

于 2019-02-04T20:15:00.470 回答
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));
于 2020-07-05T22:15:24.397 回答