segmentationfaulter segmentationfaulter - 1 month ago 8
Javascript Question

Why does this array copying not work as expected?

I am learning javascript and I am trying to copy the contents of one array to another using the following code:



var arr1 = [1, 2, 3];
var arr2 = [];

// I expect it to copy elements from arr1 to arr2
arr1.forEach(Array.prototype.push, arr2);

// I expected the length of arr2 to be 3
console.log(arr2.length); // but it logs 9





Kindly don't suggest me alternatives ways to copy array contents, I am learning JS and want to know why does it not work? Thank you

Answer

If you inspect arr2, you'll see that it contains this:

Array [ 1, 0, Array[3], 2, 1, Array[3], 3, 2, Array[3] ]

This is because forEach yields three arguments to supplied callback: element of the array, index of that element and the array itself. All those are added by your handler to arr2.