Experimenting with JavaScript today led me to discover something strange when using the spread syntax and fill() function. Here is the code I used:
let v = [...Array(9).fill([])];
function myFunc(){
arr = [1,5,2,3,4,6,8,9,7];
arr.map((val, i)=> {
v[i].push(val);
});
}
myFunc();
The resulting v-array looks like this:
Array(9) [ (9) […], (9) […], (9) […], (9) […], (9) […], (9) […], (9) […], (9) […], (9) […] ]
0: Array(9) [1,5,2,3,4,6,8,9,7]
1: Array(9) [1,5,2,3,4,6,8,9,7]
2: Array(9) [1,5,2,3,4,6,8,9,7]
3: Array(9) [1,5,2,3,4,6,8,9,7]
4: Array(9) [1,5,2,3,4,6,8,9,7]
5: Array(9) [1,5,2,3,4,6,8,9,7]
6: Array(9) [1,5,2,3,4,6,8,9,7]
7: Array(9) [1,5,2,3,4,6,8,9,7]
8: Array(9) [1,5,2,3,4,6,8,9,7]
It appears that each sub array in v was filled sequentially with the same amount of numbers. The behavior is somewhat confusing to me. However, by simply changing the initialization line from:
let v = [...Array(9).fill([])];
to:
let v = [[],[],[],[],[],[],[],[],[]];
Everything worked as expected.
Array(9) [ (1) […], (1) […], (1) […], (1) […], (1) […], (1) […], (1) […], (1) […], (1) […] ]
0: Array [ 1 ]
1: Array [ 5 ]
2: Array [ 2 ]
3: Array [ 3 ]
4: Array [ 4 ]
5: Array [ 6 ]
6: Array [ 8 ]
7: Array [ 9 ]
8: Array [ 7 ]
This serves as a reminder for those who might encounter the same issue. If anyone can provide insight into this phenomenon, I would greatly appreciate it.