数组for each传递“push”作为参数

在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) 

当然,我提出了一个build议,即上下文丢失了。 所以我试图通过这种方式来实现:

 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 itemindex和forEach被调用的array 。 所以用这些参数每次都会调用被绑定的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()提供给你的callback3个参数。

callback被调用三个参数:

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

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