Array ForEach Pass "push" As Argument
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 at Array.forEach (n
Solution 1:
Basically as per the standard syntax of forEach, it is having 3 different parameters, current item, index and the array over which the forEach is called. So push function which was bound with a will be called every time with those parameters. That is the issue here.
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])
Your code will be executed like above.
Solution 2:
Because .forEach() supplies to your callback 3 arguments.
callback is invoked with three arguments:
- the element value
- the element index
- the array being traversed
The .push() can accept any number of arguments. So, on each iteration, .push() adds those three arguments to your array.
Post a Comment for "Array ForEach Pass "push" As Argument"