gpt4 book ai didi

javascript - forEach 在循环之前是否创建数组的深拷贝?

转载 作者:数据小太阳 更新时间:2023-10-29 06:15:11 26 4
gpt4 key购买 nike

举个例子

arr1 = [{ b: 2 }, { a: 1 }] // an array with 2 elements

arr1.forEach(function (element, index, array) {

console.log(element);
console.log('of');
console.log(array);
console.log('');


arr1.push({ c: 3 });
});

console.log(arr1);

结果

{ b: 2 }
of
[ { b: 2 }, { a: 1 } ]

{ a: 1 }
of
[ { b: 2 }, { a: 1 }, { c: 3 } ]

[ { b: 2 }, { a: 1 }, { c: 3 }, { c: 3 } ]

在上面的示例中,我正在遍历一个数组并向其添加更多值,并且在循环时将它们添加到原始数组中

forEach是否使用不同的数组来循环?

最佳答案

它没有使用不同的数组,如您所见,当您 console.log(array); 时,您仍然会看到新元素,即使您将它们推送到 arr1。所以我们知道 arrayarr1 指向同一个数组。

不管 forEach 做什么,至少根据 polyfill on MDN , 这是:

在迭代之前,它会提取数组的长度,然后才开始迭代。因此,如果传递给 forEach 的函数中数组的长度发生变化,则迭代不会发生变化。

// 2. Let lenValue be the result of calling the Get() internal
// method of O with the argument "length".
// 3. Let len be toUint32(lenValue).
var len = O.length >>> 0;



// 6. Let k be 0
k = 0;

// 7. Repeat, while k < len
while (k < len) {
...
}

关于javascript - forEach 在循环之前是否创建数组的深拷贝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38866510/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com