The array fill method has pitfalls
Suppose now you want to create an array with a length of 3 and all elements are -1, it is very simple, right:
-
cycle
-
fill
filling
Don’t write the cycle, just look at fill
the method , as follows:
const arr1 = new Array(3).fill(-1);
console.log(arr1);
There seems to be no problem, don't panic, let's see again.
Suppose you want to create a two-dimensional array whose 3*3 elements are all -1? The idea is almost right:
-
double loop
-
two
fill
fills
I don’t want to write the double loop anymore, just use fill to realize it. Let’s go, I don’t know how you would write it. This is how Xiaosheng wrote it. Is it okay for the guest officer?
const arr2 = new Array(3).fill(new Array(3).fill(-1));
console.log(arr2);
Xiaosheng said, this is possible, if you don’t believe me, let’s execute it and see the result
[
[ -1, -1, -1 ],
[ -1, -1, -1 ],
[ -1, -1, -1 ]
]
Looks like nothing wrong with it, awesome!
But is it really okay? ? Well, to be clear, this is a big problem, let's look at the following code
const arr2 = new Array(3).fill(new Array(3).fill(-1));
arr2[0][0] = 1;
arr2[1][1] = 2;
arr2[2][2] = 3;
console.log(arr2);
Here we do something very simple
- Set the element in row 1 and column 1 to 1
- Set the element in row 2 and column 2 to 2
- Set the element in row 3 and column 3 to 3
According to normal logic, here should be the following output:
[
[ 1, -1, -1 ],
[ -1, 2, -1 ],
[ -1, -1, 3 ]
]
Well, normally it should be like this, but in reality?
[
[ 1, 2, 3 ],
[ 1, 2, 3 ],
[ 1, 2, 3 ]
]
Hey, why did it become like this, it is actually very simple, if fill
the object filled by the method , then each filled element is a shallow copy of this object, that is, an object with the same memory address. That's why this happens, so when fill
using , once the object is filled, you must be extra careful.
Finally, let’s give a quick method of generating a two-dimensional array commonly used by Xiaosheng himself:
const arr3 = new Array(3).fill(-1).map(() => new Array(3).fill(-1));
console.log(arr3);