1

when I init use fill to init a 2D array like this

    let dp = new Array(n);
    dp.fill(new Array(n).fill(false));

if I change the dp[0][0] it will be

[
  [ true, false, false, false, false ],
  [ true, false, false, false, false ],
  [ true, false, false, false, false ],
  [ true, false, false, false, false ],
  [ true, false, false, false, false ]
]

but if I use the below code to init a array, there is the result I need, what's the reason?

let dp = new Array(n);
for(let k = 0; k < n; k++){
    dp[k] = new Array(n).fill(false)
}
  • 1
    When you use `.fill` you don't make *copies* of the array, but you have *literally* the same array in every slot. – VLAZ Apr 27 '20 at 16:19
  • https://stackoverflow.com/questions/38940576/javascript-why-array-prototype-fill-actually-fills-a-pointer-of-object-when https://stackoverflow.com/questions/35578478/array-prototype-fill-with-object-passes-reference-and-not-new-instance https://stackoverflow.com/questions/37949813/array-fillarray-creates-copies-by-references-not-by-value https://stackoverflow.com/questions/27613126/unexpected-behavior-using-array-map-on-an-array-initialized-with-array-fill https://stackoverflow.com/questions/50807131/how-do-i-use-array-fill-for-creating-an-array-of-objects – VLAZ Apr 27 '20 at 16:22

1 Answers1

0

That happens because dp.fill() is using a reference to the same array, defined by new Array(n).fill(false). When you change dp[0], you also "change" dp[1], dp[2], etc...

So you should use the code you posted below.

D. Pardal
  • 6,173
  • 1
  • 17
  • 37