2

I'm trying to avoid hardcoding 2d matrix grids by using JavaScript new Array(). In theory, it works, but in practice, I receive a bug. While a hardcoded grid swaps nearest gems correctly, the new Array method swaps them almost randomly with the same code

me.tileGrid = new Array(6).fill(new Array(6).fill(null));
 /* The upper code is potentially scalable, but it doesn't work same */
 me.tileGrid = [
      [null, null, null, null, null, null],
      [null, null, null, null, null, null],
      [null, null, null, null, null, null],
      [null, null, null, null, null, null],
      [null, null, null, null, null, null],
      [null, null, null, null, null, null]
    ];
James Tomasino
  • 3,520
  • 1
  • 20
  • 38

1 Answers1

1

The reason is usage of fill(). When you will an array with objects(reference type) then each element refer to the same value in memory. According to MDN

The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length).

The above "static value" means that first an array Array(6).fill(null) is create and that same is added to the main array six times. Means that if you will change one of them all will change.

The below snippet is the proof for above discussion

const x = new Array(6).fill(new Array(6).fill(null));
console.log(x[0] === x[1])

You can use spread operator and then use map() and also note that you don't need use new with array. new Array and Array are same

const x = [...Array(6)].map(x => Array(6).fill(null))
console.log(x[0] === x[1])
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73