用随机数填充Javascript中的2D数组 [英] Populating a 2D array in Javascript with random numbers

查看:89
本文介绍了用随机数填充Javascript中的2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to populate a 2D array in javascript with random numbers. 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

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

推荐答案

问题是您没有初始化该行.很容易解决:

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

这是一个更干净的版本,与Code Maniac的版本有些相似,但进行了一些简化:

This is a cleaner version, somewhat similar to the one from Code Maniac, but simplified a bit:

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

这篇关于用随机数填充Javascript中的2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆