3

the problem I have is when I associate value in the 2d array on a certain row and column, that value will be stored on several rows on the same column

var Matrix = Array(3).fill(Array(3).fill(0));
console.log(Matrix);
Matrix[1][2]=1;
console.log(Matrix);
and the output is : 

/// the 2d array 
[ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]
/// after 'Matrix[1][2]=1'
[ [ 0, 0, 1 ], [ 0, 0, 1 ], [ 0, 0, 1 ] ]

1 Answers1

1

The tree sub-arrays you are declared in the first line, are refered to the same array, like a pointer.

try something like this:

var Matrix = []
Matrix.push(Array(3).fill(0))
Matrix.push(Array(3).fill(0))
Matrix.push(Array(3).fill(0))
console.log(Matrix);
Matrix[1][2]=1;
console.log(Matrix);

Output

/// the 2d array 
[ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]
/// after 'Matrix[1][2]=1'
[ [ 0, 0, 0 ], [ 0, 0, 1 ], [ 0, 0, 0 ] ]
Nicolas Acosta
  • 742
  • 5
  • 12