0

What is intended behavior for += with 2D arrays in JavaScript?

let  matrix = new Array(3).fill(new Array(3).fill(0));
matrix[0][0] += 1;
console.log(matrix); //[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

Why the output is

[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

and not

[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

Is this intended behavior?

j08691
  • 204,283
  • 31
  • 260
  • 272
m0z3e
  • 1
  • 3
    `Array.fill` will place *the same* array in every slot. So you are changing `[0]` but `[1]` and `[2]` also point at the same object. – VLAZ Jun 27 '20 at 21:32
  • Pasted your code into a snippet and the output I get is `[ [ /**id:2**/ 1, 0, 0 ], /**ref:2**/, /**ref:2**/ ]` – j08691 Jun 27 '20 at 21:34

0 Answers0