1

For example:

> var aryA = [];
undefined
> var aryB = [1, 2, 3];
undefined    
> aryB.forEach(aryA.push.bind(aryA));
undefined
> aryA
[1, 0, Array[3], 2, 1, Array[3], 3, 2, Array[3]]

Yes, I want to copy the elements from aryB to aryA. Of course I have other solutions, but why doesn't this method work?
Please forgive if this is a duplicate question. I am a Stackoverflow newcomer.

Li Enze
  • 679
  • 2
  • 5
  • 18

1 Answers1

2

Well, it does "work". .forEach passes three arguments to the callback:

  1. the current array element
  2. the index of the current array element
  3. the array itself (i.e. that .forEach was called upon)

Since you are passing push as callback, you are essentially performing the following call in each iteration:

aryA.push(aryB[i], i, aryB);

i.e. adding three values to the array, which is exactly what you are seeing as the result:

[1, 0, Array[3], 2, 1, Array[3], 3, 2, Array[3]]
 ^  ^  ^         ^  ^  ^
 |  | array      |  |  array
 | 1. index      | 2. index      ...
1. element      2. element

I guess you just want to push the first argument, in which case you have to pass a function calls .push with only the first argument.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143