简体   繁体   English

为什么数组将空数组推入另一个?

[英]Why does the array push an empty array into another?

Why is the value of array2 [[], [], [], [], []] at the end of the loop? 为什么array2 [[], [], [], [], []]的值在循环结束时?

 var array1 = []; var array2 = []; for (let i = 1; i <= 10; i++) { array1.push(i); if (i % 2 === 0) { //console.log(array1); array2.push(array1); array1.length = 0; }; }; console.log(array1); console.log(array2); 

Can anyone explain, what's going on in this code? 任何人都可以解释一下,这段代码中发生了什么?

Arrays in JavaScript are mutable structures. JavaScript中的数组是可变结构。 array1 is getting emptied out each time by assigning 0 to length . 通过将0分配给length ,每次都会清空array1 Theres only 5 even numbers between 1 and 10 (namely: 2, 4, 6, 8, 10), so array2 has 5 references to array1 in it. 在1和10之间只有5个偶数(即: array2 ),因此array2有5个对array1引用。

It is because of array1.length = 0; 这是因为array1.length = 0; .

You are pointing the same array reference and setting it to empty. 您指向相同的数组引用并将其设置为空。

So technically you are pushing a new empty array for every even number in the iteration. 所以从技术上讲,你在迭代中为每个偶数推送一个新的空数组。

The other answers have already explained what's going on, here's what to do to get what you expected: 其他答案已经解释了发生了什么,这里是做什么来达到你的期望:

 var array1 = []; var array2 = []; for (let i = 1; i <= 10; i++) { array1.push(i); if (i % 2 === 0) { //console.log(array1); array2.push([...array1]); array1.length = 0; }; }; console.log(array1); console.log(array2); 

You can simply use a new ECMAScript feature called array destructuring [...arr] (destructuring into a new array), which creates a shallow copy of the array it is applied on. 您可以简单地使用名为array destructuring [...arr]的新ECMAScript功能(解构为新数组),该功能会创建应用它的数组的浅表副本。

Because when you push an array / object variable, you are storing the reference, not the value. 因为当您按下数组/对象变量时,您将存储引用,而不是值。 Making array1 length equals to 0 as you know you are deleting array1 values, and this cause the result you are seeing for array2. 使array1的长度等于0,因为您知道要删除array1值,这会导致您在array2中看到的结果。

If you want to have the behaviour you expect you can create a new array before each push like: 如果你想拥有你期望的行为,你可以在每次推送之前创建一个新数组,如:

var array1 = [];
var array2 = [];

for (let i = 1; i <= 10; i++) {
  array1.push(i);
  if (i % 2 === 0) {
    array2.push(Array.from(array1));
    array1.length = 0;
  };
};
// []
console.log(array1);
// [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9, 10 ] ]
console.log(array2);

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

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