简体   繁体   English

Javascript Array.push方法问题

[英]Javascript Array.push method issue

I have the following code: 我有以下代码:

function build_all_combinations(input_array){
   array = [1,2,3]
   limit = array.length - 1
   combo = []

   for(i = 0; i<= limit; i++){
      splice_value = array.splice(0,1)
      push_value = splice_value[0]
      array.push(push_value)
      console.log(array) 
      combo.push(array) 
   }
   console.log(combo) 
}

Which outputs: 哪个输出:

[2, 3, 1]
[3, 1, 2]
[1, 2, 3]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

The last line should be: [[2, 3, 1],[3, 1, 2],[1, 2, 3]] 最后一行应该是: [[2, 3, 1],[3, 1, 2],[1, 2, 3]]

I'm obviously not grokking something about the way the array is working. 我显然不对数组的工作方式有所了解。 Each individual array is correct, but when I go to push them to the combo array, something is failing along the way. 每个单独的数组都是正确的,但是当我将它们推到组合数组时,在此过程中出现了一些故障。 What is it? 它是什么?

Each time you are pushing the same array into the combo array; 每次将同一个数组推入组合数组时; ie, all the references are pointing to the same instance in memory. 也就是说,所有引用都指向内存中的同一实例。 So when you update one, you've in reality updated them all. 因此,当您更新一个时,实际上您已经对它们全部进行了更新。

If you want separate references, you'll need to create separate arrays. 如果需要单独的引用,则需要创建单独的数组。

shift and slice are your friends here: shiftslice是您的朋友在这里:

var array = [1,2,3];
var combo = []
for(var i = 0; i<array.length; i++){
  array.push(array.shift());  // remove first element (shift) and add it to the end (push)
  combo.push(array.slice());  // add a copy of the current array to combo
}

DEMO 演示

jordan002 has given the explanation for this behaviour. jordan002已经对此行为进行了解释。

Here's the workaround. 这是解决方法。

array = [1,2,3]
limit = array.length - 1
combo = []
for(i = 0; i<= limit; i++){
 splice_value = array.splice(0,1)
 push_value = splice_value[0];
 array.push(push_value);
 console.log(array);
 combo.push(array.concat([]));
}
console.log(combo);  

You can store a copy in temp variable. 您可以将副本存储在temp变量中。

array = [1,2,3]
limit = array.length - 1
combo = []
for(i = 0; i<= limit; i++){
 splice_value = array.splice(0,1)
 push_value = splice_value[0];
 array.push(push_value);
 console.log(array);
 var temp = array.slice();  
 combo.push(temp);
}
console.log(combo) 

Reference 参考

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

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