How can I declare and fill at the same time an array of arrays (matrix) using the JavaScript Array fill() Method?

时间:2022-09-20 21:28:48

I tried to make an array and then to map over it and declare new arrays but failed miserably.

我试图制作一个数组然后映射它并声明新的数组但是失败了。

let matrix = (new Array(5).fill(0)).map(new Array(5).fill(0));

2 个解决方案

#1


1  

function matrix(size) {
  return new Array(size).fill(0).map(el => Array(size).fill(0));
}

console.log(matrix(4));

#2


1  

I like the following solution

我喜欢以下解决方案

Array.apply(0, {length: 5}).map(function() {return Array(5).fill(0)})

#1


1  

function matrix(size) {
  return new Array(size).fill(0).map(el => Array(size).fill(0));
}

console.log(matrix(4));

#2


1  

I like the following solution

我喜欢以下解决方案

Array.apply(0, {length: 5}).map(function() {return Array(5).fill(0)})