Array forJeder Pass "push" als Argument
Faced seltsames Problem in JS. Ich erhalte folgende Fehlermeldung:
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)
Klar, ich habe einen Vorschlag gemacht, dass der Kontext verloren geht. Also versuche ich das auf diese Weise zu erreichen:
b.forEach([].push.bind(a))
Das Ergebnis wird unvorhersehbar:
[ 1, 0, [ 1, 2, 3 ], 2, 1, [ 1, 2, 3 ], 3, 2, [ 1, 2, 3 ] ]
WAS? =) Woher kommt 0? Okay, vielleicht ist es ein "Glitch" -Index, aber warum nicht zuerst als? :)
Um es klar zu machen, dies funktioniert auf klassische Weise, und das ist keine Frage:
b.forEach(el => a.push(el) )
ann jemand dieses seltsame Verhalten erkläre