I want to iterate over an array and consecutively push them into another array after adding the first n numbers:
let arr = []
let iniArr = [...Array(9).keys()].map(item=>1)
let push = iniArr.slice(0,3).reduce((total,num)=>total num)
for (let i = 0; i < 3; i ) {
iniArr.splice(i,3)
iniArr.splice(i,0,push)
arr.push(iniArr)
}
I don't get what is expected but the final result of the whole iteration for each push:
(3) [Array(3), Array(3), Array(3)]
0: (3) [3, 3, 3]
1: (3) [3, 3, 3]
2: (3) [3, 3, 3]
However if I console.log them I get back the results I want in the array:
for (let i = 0; i < 3; i ) {
iniArr.splice(i,3)
iniArr.splice(i,0,push)
console.log(iniArr)
}
(7) [3, 1, 1, 1, 1, 1, 1]
(5) [3, 3, 1, 1, 1]
(3) [3, 3, 3]
Can someone explain why does it happen?
CodePudding user response:
I have to use spread syntanx,
arr.push([...iniArr])
//instead of
arr.push(iniArr)
but I still don't get why.
CodePudding user response:
You are pushing the reference of iniArr
3 times to the arr
, and any time the iniArr
data changes, the arr
respectfully display that.
As you find out, when you pass the values of the iniArr
like [...iniArr]
and these values are primitive(like numbers that you are using here), so they push to the arr
with their values, and not changing, no matter what happened to the iniArr