问题描述:

This question already has an answer here:

  • Unexpected behavior using Array Map on an Array Initialized with Array Fill

    1 answer

网友答案:

The Array#fill method filling with the same array that the elements are the reference to a single array. So you need to create separate arrays as elements. So updating one will reflect all other since they are not different array they are the same.

Using Array.from() you can create and generate values by map function.

const column = 10;
const row = 10;

let matrix = Array.from({
  // create array of length `row`
  length: row 
  // map function to generate values
}, () => new Array(column).fill(0));

matrix[0][1] = 1;

console.log(matrix)
网友答案:

@PranavCBalan have right.

It's something like that:

let matrix = new Array(row);
var x = new Array(column).fill(0);
matrix[0] = matrix[1] = .. = matrix[column - 1] = x;

Your matrix is array of the one object.

相关阅读:
Top