I was writing a tetris mini-game and needed to build the map using a TWO-DIMENSIONAL array. The first thing I did was initialize the two-dimensional array, instinctively, and use two for loops (a stupid way) :

let map = []
for (let i = 0; i < 10; i++) {
  let arr = []
  for (let j = 0; j < 10; j++) {
    arr[j] = 0
  }
  map.push(arr)
}
Copy the code

As a ‘lazy’ programmer, I wouldn’t allow this, so I came up with the fill() method, which looks like this:

let map = new Array(10).fill(new Array(10).fill(0))
Copy the code

But when I do the assignment:

map[0] [0] = 10
/ * [[3, 0, 0, 0, 0, 0, 0, 0, 0, 0], [3, 0, 0, 0, 0, 0, 0, 0, 0, 0], [3, 0, 0, 0, 0, 0, 0, 0, 0, 0]]... * /
Copy the code

F12 Open the Google Debug panel, enter the Memory panel, find sure enough, the declared array Memory points to the same address:

Create a new array and return it with a map() method. Create an array and return it with a map() method.

let arr = Array.from(new Array(10)).map(() = > new Array(10).fill(0))

let arr = [...(new Array(10))].map(() = > new Array(10).fill(0))
Copy the code

Go to the Memory panel and recreate the snapshot:

After that, normal assignment operations can be performed. It is highly recommended that you check out the Memory panel.