Заполнение 2D-массива в Javascript случайными числами

Я пытаюсь заполнить 2D-массив в 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) ;

2 ответа

Решение

Проблема в том, что вы не инициализируете строку. Это легко исправить:

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 Stackru'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 Stackru's

Один из способов сделать это с помощью карты

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

console.log(op)

Этого можно добиться с помощью комбинации 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 на 964, полный случайных чисел от 900 до 1000, используя следующее:

new Array(100).fill([]).map(x => Array(964).fill(0).map(x => x + Math.floor(Math.random() * (1000 - 900)) + 900));
Другие вопросы по тегам