Array forEach pass "push"作为参数

Array forEach pass "push" as argument

本文关键字:quot 参数 push Array forEach pass      更新时间:2023-09-26

面对JS中的奇怪问题。我收到这个错误:

let a = []
let b = [1,2,3]
b.forEach(a.push)
TypeError: Array.prototype.push called on null or undefined
    at Array.forEach (native)
    at repl:1:3
    at REPLServer.defaultEval (repl.js:262:27)
    at bound (domain.js:287:14)
    at REPLServer.runBound [as eval] (domain.js:300:12)
    at REPLServer.<anonymous> (repl.js:431:12)
    at emitOne (events.js:82:20)
    at REPLServer.emit (events.js:169:7)
    at REPLServer.Interface._onLine (readline.js:211:10)
    at REPLServer.Interface._line (readline.js:550:8)

当然,我已经提出了一个建议,上下文丢失了。所以,我试着用这种方式来完成:

b.forEach([].push.bind(a))

结果变得不可预测:

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

什么?0是从哪里来的?好吧,也许是"故障"指数,但为什么不先比?:)

说明一下,这是以经典的方式工作的,这不是一个问题:

b.forEach(el => a.push(el) )
有人能解释一下这种奇怪的行为吗?

基本上按照forEach的标准语法,它有3个不同的参数,current item, indexarray,在这些参数上调用forEach。因此,与a绑定的push函数每次都会调用这些参数。这就是问题所在。

iteration 1 : a.push(1,0,[1,2,3]) //since a was bound with push
iteration 2 : a.push(2,1,[1,2,3])
iteration 3 : a.push(3,2,[1,2,3])

你的代码将像上面那样执行

因为.forEach()为你的回调提供了3个参数

回调有三个参数:

  1. 元素值
  2. 元素索引
  3. 正在遍历的数组

.push()可以接受任意数量的参数。因此,在每次迭代中,.push()将这三个参数添加到数组中。