填充在Javascript的2D阵列与随机数

问题描述 投票:0回答:2

我试图填充在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) ;
javascript arrays random auto-populating
2个回答
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

更新

这是一个更清洁的版本,有点类似于从代码疯子的人,但简化了一下:

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
投票

这样使用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)
© www.soinside.com 2019 - 2024. All rights reserved.