Array forEach传递"push"作为参数

Laz*_*ert 2 javascript arrays lambda node.js

面对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)
Run Code Online (Sandbox Code Playgroud)

当然,我已经提出了一个建议,即背景丢失了.所以,我尝试以这种方式实现这一目标:

b.forEach([].push.bind(a))
Run Code Online (Sandbox Code Playgroud)

结果变得不可预测:

[ 1, 0, [ 1, 2, 3 ], 2, 1, [ 1, 2, 3 ], 3, 2, [ 1, 2, 3 ] ]
Run Code Online (Sandbox Code Playgroud)

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

为了说清楚,这是一种经典的方式,这不是一个问题:

b.forEach(el => a.push(el) )
Run Code Online (Sandbox Code Playgroud)

有人能解释这种奇怪的行为吗?

Raj*_*amy 7

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

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])
Run Code Online (Sandbox Code Playgroud)

您的代码将像上面一样执行.

  • 长话短说:OP试图写出"智能"代码.经验教训:避免编写"智能"代码.:) (2认同)