简体   繁体   中英

Binding Array.push

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?

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM