Why can't we directly redirect Array.prototype.concat to shorthand?

JavaScript newbie here. Today I found out about reduceand decided to implement my own array smoothing function.

What I had was

var array = [[1, 2], [3, 4, 5], [6]];
var result = array.reduce(Array.prototype.concat, []); // Causes Uncaught TypeError: Array.prototype.concat called on null or undefined
var result = array.reduce(Array.prototype.concat.call, []); // Causes Uncaught TypeError: undefined is not a function

Whereas the answers in Combine / smooth an array of arrays in JavaScript? are elegant and idiomatic, I would really appreciate the illustration of failed attempts.

+4
source share
3 answers

You have the right idea with Array.prototype.concat.call. Using Array.prototype.concatcalls will look like this:

var concat = Array.prototype.concat;

concat(concat(concat([],
                     [1, 2]),
              [3, 4, 5]),
       [6])

, Array.prototype.concat this; concat(), this undefined. call?

var call = Array.prototype.concat.call;

call(call(call([],
               [1, 2]),
          [3, 4, 5]),
     [6])

, Function.prototype.call (Array.prototype.concat , , call Function.prototype). call this, call(), this undefined.

Function.prototype.call.bind(Array.prototype.concat)..., reduce , . , , , Array.prototype.concat, .

+2

result = array.reduce(fn, []);
function fn(a, b, index, array) { // this is the arguments reduce sends to the callback
    return Array.prototype.concat.call(null, a, b, index, array);
}

?

+3

This is because it Array.prototype.concatrequires a function prototype to integrate an array or list of values ​​into a main array.

However callback Array.prototype.reducerequires accumulator, currentValue, currentIndexand arrayas parameters.

The parameters (and also what they should do) do not match and therefore you get unexpected results or errors.

0
source

Source: https://habr.com/ru/post/1670017/


All Articles