JS, difference in array matrix and forEach behavior

后端 未结 3 1596
太阳男子
太阳男子 2021-01-19 19:53

I was doing some training tasks for my JS course and I got one where you must implement a function that takes a positive integer (n) and returns a matrix like the one below

3条回答
  •  北海茫月
    2021-01-19 20:32

    It's because Array is a reference type. When you do

    new Array(n).fill(new Array(n).fill(0))

    first the inner new Array(n).fill(0) makes an array size n filled with 0; next the outer Array(n).fill creates an array filled with n references to that inner array.

    It doesn't create n inner arrays, just n references to the same array. So when you change an element of that inner array, all the references in the outer array will reflect the change since they all point to the same object.

提交回复
热议问题