为什么我们不能将 Array.prototype.concat 直接输入到 reduce 中?



javascript newbie在这里。今天,我了解了reduce,并着手实现自己的数组扁平功能。

我所拥有的

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

虽然在合并/弄平了javaScript中的数组中的答案?优雅而愚蠢,我真的很感谢我的尝试失败的插图。

您的代码等效于

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);
}

您可以发现问题吗?

您对Array.prototype.concat.call有正确的想法。使用Array.prototype.concat,呼叫将看起来像这样:

var concat = Array.prototype.concat;
concat(concat(concat([],
                     [1, 2]),
              [3, 4, 5]),
       [6])

它不起作用,因为Array.prototype.concat将其参数与this相连;将其称为concat(),将其称为this的CC_7。使用call呢?

var call = Array.prototype.concat.call;
call(call(call([],
               [1, 2]),
          [3, 4, 5]),
     [6])

这遇到了相同的问题,但是使用Function.prototype.callArray.prototype.concat与其他任何函数一样,并且从Function.prototype继承其call方法)。call试图调用其this,但称其为call(),它给了undefinedthis

您可以通过Function.prototype.call.bind(Array.prototype.concat)…如果reduce没有用更多参数调用其功能,而不是累加器和当前项目。但是确实如此,通过当前项目和上下文数组的索引,并破坏了仅通过用某些内置的Array.prototype.concat传递CC_21来制作此工作的机会。

之所

但是,对Array.prototype.reduce的回调需要accumulatorcurrentValuecurrentIndexarray作为参数。

参数(以及他们应该做的事情)不匹配,因此您会得到意外的结果或错误。

最新更新