Does forEach create a deep copy of the array before the loop?

Here is an example

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);

Result

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

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

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

In the above example, I look at the array and add more values ​​to it, and they are added to the original, and the loop

Does forEachanother loop use for loop?

+4
source share
2 answers

It does not use another array, as you can see that when you console.log(array);, you will still see new elements, even if you pushed them to arr1. So, we know that arraythey arr1point to the same array.

However, what forEachdoes, at least according to the polyfill in MDN , is this:

. , , 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) {
    ...
}
+2

Source: https://habr.com/ru/post/1650769/


All Articles