Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding Array.push

Tags:

javascript

I was trying to pass the 'push' method of array directly to forEach invocation on another array:

result = []
l1 = [1]
f = result.push.bind(result)
l1.forEach(f)

And the result ends up:

> result
[ 1, 0, [ 1 ] ]

If I do, instead:

l1.forEach(function (x) { f(x); })

Then everything works fine. What is going on?

like image 799
Vladimir Prus Avatar asked Sep 02 '26 15:09

Vladimir Prus


1 Answers

To understand what is going on run this code snipped

[1].forEach(function() {
    console.log(arguments);
});

And you'll receive

[1, 0, Array[1]]

Function, supplied to forEach method is called for each array element with the following arguments:

  1. Array element
  2. Element position
  3. Array itself

So, it seems like you can't do what you want with binding a push call to specific array instance...

like image 155
Olegas Avatar answered Sep 04 '26 05:09

Olegas