【发布时间】:2016-12-31 12:57:05
【问题描述】:
在 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) )
有人能解释一下这种奇怪的行为吗?
【问题讨论】:
标签: javascript arrays node.js lambda