简体   繁体   English

用随机数在 Javascript 中填充二维数组

[英]Populating a 2D array in Javascript with random numbers

I'm trying to populate a 2D array in javascript with random numbers.我正在尝试用随机数填充 javascript 中的二维数组。 Although each column in the array is random, each row is identical which is not what I want (see image below).虽然数组中的每一列都是随机的,但每一行都是相同的,这不是我想要的(见下图)。 I want both rows and columns to be random.我希望行和列都是随机的。

http://eeldesigns.com/image.jpg 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) ;

One way of doing this using 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)

The trouble is that you're not initializing the row.问题是您没有初始化该行。 It's easily fixed:它很容易修复:

 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

Update更新

This is a cleaner version, somewhat similar to the one from Code Maniac, but simplified a bit:这是一个更简洁的版本,有点类似于 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

This can be accomplished using a combination of Array.prototype.fill() and Array.prototype.map() :这可以使用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));

For example, we can create a 100 by 964 column array full of random numbers between 900 and 1000 using the following:例如,我们可以使用以下命令创建一个 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM