我试图填充在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) ;
麻烦的是,你不初始化行。它很容易固定:
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
这样使用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)