简体   繁体   English

将拼接后的数组推送到 JavaScript 中的空数组

[英]Push spliced array to empty array in JavaScript

I want to iterate over an array and consecutively push them into another array after adding the first n numbers:我想遍历一个数组并在添加前 n 个数字后将它们连续推入另一个数组:

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:但是,如果我 console.log 它们我会在数组中返回我想要的结果:

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?有人可以解释为什么会这样吗?

I have to use spread syntanx,我必须使用传播语法,

arr.push([...iniArr]) 
//instead of
arr.push(iniArr)

but I still don't get why.但我仍然不明白为什么。

You are pushing the reference of iniArr 3 times to the arr , and any time the iniArr data changes, the arr respectfully display that.您将iniArr的引用推送到arr 3 次,并且任何时候iniArr数据更改, arr都会恭敬地显示它。

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正如您所发现的,当您像[...iniArr]一样传递iniArr的值并且这些值是原始的(就像您在此处使用的数字一样)时,它们会将它们的值推送到arr ,而不是改变,不不管iniArr发生了什么

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM