Javascript 数组forEach pass“;推;作为论据
在JS中遇到了奇怪的问题。我收到以下错误消息:Javascript 数组forEach pass“;推;作为论据,javascript,arrays,node.js,lambda,Javascript,Arrays,Node.js,Lambda,在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:
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)
结果变得不可预测:
[ 1, 0, [ 1, 2, 3 ], 2, 1, [ 1, 2, 3 ], 3, 2, [ 1, 2, 3 ] ]
什么?=)0来自哪里?好吧,也许是它的“小故障”——索引,但为什么不首先呢
只是想说明一下,这是一种经典的方式,这不是一个问题:
b.forEach(el => a.push(el) )
有人能解释这种奇怪的行为吗?基本上按照的标准语法,它有3个不同的参数,
当前项
,索引
和调用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个参数
使用三个参数调用回调:
元素值
元素索引
正在遍历的数组
.push()
可以接受任意数量的参数。因此,在每次迭代中,.push()
都会将这三个参数添加到数组中。长话短说:OP试图编写“智能”代码,这是自作自受。教训:避免编写“智能”代码。:)谢谢,我不应该错过这个。谢谢你的回答,这变得更清楚了。
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])