Array forEach pass “push” as argument

后端 未结 2 493
梦毁少年i
梦毁少年i 2021-01-21 15:54

Faced strange issue in JS. I receive error on this:

let a = []
let b = [1,2,3]
b.forEach(a.push)
TypeError: Array.prototype.push called on null or undefined
             


        
2条回答
  •  广开言路
    2021-01-21 16:51

    Because .forEach() supplies to your callback 3 arguments.

    callback is invoked with three arguments:

    1. the element value
    2. the element index
    3. the array being traversed

    The .push() can accept any number of arguments. So, on each iteration, .push() adds those three arguments to your array.

提交回复
热议问题