我正在学习关于 Javascript Functional Programming 的在线类(class) 在练习 16 中,它向您展示了 reduce 是如何实际实现的,以帮助您理解如何使用它,但是在这个实现中有一些我实际上没有得到的东西,我将展示代码:
Array.prototype.reduce = function(combiner, initialValue) {
var counter, accumulatedValue;
// If the array is empty, do nothing
if (this.length === 0) {
return this;
}
else {
// If the user didn't pass an initial value, use the first item.
if (arguments.length === 1) {
counter = 1;
accumulatedValue = this[0];
}
else if (arguments.length >= 2) {
counter = 0;
accumulatedValue = initialValue;
}
else {
throw "Invalid arguments.";
}
// Loop through the array, feeding the current value and the result of
// the previous computation back into the combiner function until
// we've exhausted the entire array and are left with only one value.
while(counter < this.length) {
accumulatedValue = combiner(accumulatedValue, this[counter])
counter++;
}
return [accumulatedValue];
}
};
我不明白第一个 if 语句,当它检查 this.length
时,这到底是什么意思?
Take note this is different from the reduce in ES5, which returns an value instead of an Array, this is used just as a sample for the learning purpose.
最佳答案
Array.prototype.reduce = function(...
是说,“在 Array 的原型(prototype)上创建一个函数”——这意味着新的 reduce
函数将可以在所有数组上调用,例如:
[1, 2, 3].reduce(...
这意味着您也可以在空数组上调用它,例如:
[].reduce(...
基于评论:
If the array is empty, do nothing
您正在处理一个数组,当函数被调用时,this
被设置为调用 reduce
的数组。 reduce
的实现假定如果该数组为空(即 this.length === 0
),您不能在逻辑上进一步减少它 - 没有什么可以减少,因此您可以返回相同的空数组。
正如@Alnitak 在评论中指出的那样,与the specification 相比,reduce
的这种实现存在缺陷。 . the MDN 上提供了不同的实现用于填充旧浏览器。
关于javascript - check for this.length into a function 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34595902/