1

Ok, this is driving me crazy. I've reviewed the docs, exemples, questions but I don't know what is happening. Lets get this oversimplified example:


let arr = Array(12).fill(Array(12));

// Ok. If I log arr it shows an array of 12 arrays all length 12, as I expected.

for(let i = 0; i < 12; i++) {
   for(let j = 0; j < 12; j++) {
      arr[0][j] = 'black';
   }
}

console.log(arr)

Ok, shouldn't only the first array been filled with 'black' while the others stay empty? Why I'm getting all the arrays filled with 'black'? I know the code above is useless but this behavior is messing with something I'm doing.

What am I missing?

  • Don't `.fill` with non-primitives, otherwise you'll only have one such non-primitive in memory - use `Array.from` instead, to explicitly create the inner non-primitive on each iteration. `arr = Array.from({ length: 12 }, () => Array(12))` – CertainPerformance Apr 25 '19 at 00:24
  • All of the elements of your array point to the same sub-array. So when you modify one of them, all of them get modified. You need to create a separate sub-array for each element. – Benjamin Davies Apr 25 '19 at 00:28
  • Oh ok, I see. Thanks. – Matheus Traldi Apr 25 '19 at 20:19

0 Answers0