这是一个例子
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);
Run Code Online (Sandbox Code Playgroud)
结果
{ b: 2 }
of
[ { b: 2 }, { a: 1 } ]
{ a: 1 }
of
[ { b: 2 }, { a: 1 }, { c: 3 } ]
[ { b: 2 }, { a: 1 }, { c: 3 }, { c: 3 } ]
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,我遍历一个数组并向其中添加更多值,并在循环时将它们添加到原始数组中
是否forEach使用不同的阵列,以循环?
正如您所看到的,它没有使用不同的数组,当您 时console.log(array);,您仍然会看到新元素,即使您将它们推送到 上arr1。所以我们知道这一点array并arr1指向同一个数组。
然而forEach,至少根据MDN 上的 polyfill来看,它的作用是:
在迭代之前,它将提取数组的长度,然后才开始迭代。因此,如果数组的长度在您传递给 的函数内发生变化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) {
...
}
Run Code Online (Sandbox Code Playgroud)