我想创建一个执行以下操作的函数(reduce):
地点:
var collection = [1, 2, 3];
和
function iterator(total, element) {
return total + element;
};
如果initial
定义为3
:
reduce(collection, iterator, 3)
会这样做:
3 + 1
4 + 2
6 + 3 = 9
如果初始
是未定义
:
reduce(collection, iterator)
会这样做:
1 + 2
3 + 3 = 6
这是我的代码:
var reduce = function(collection, iterator, initial) {
if (initial === undefined) {
var total = 0;
} else {
var total = initial;
}
each(collection, function(element) {
total = iterator(total, element);
});
return total;
}
它可以工作,但您可以看到我已经硬编码了 total = 0
,但我希望此代码能够在其他场景中工作(例如,乘法,我不希望0 使整个产品为 0)。
最佳答案
这就是我的实现方式:
alert(reduce([1,2,3], add, 3)); // 9
alert(reduce([1,2,3], add)); // 6
function add(a, b) {
return a + b;
}
function reduce(array, iterator, initial) {
var length = array.length;
var index = 0;
if (arguments.length < 3) {
if (length > 0) var result = array[index++]; // Note 1
else throw new Error("Reduce of empty array with no initial value");
} else var result = initial;
while (index < length) result = iterator(result, array[index++]);
return result;
}
该代码非常不言自明。不过,它的工作原理如下,如果传递的参数数量小于 3,则意味着未给出 initial
。因此,我们将 result
设置为 array[0]
并递增 index
。如果array
为空,那么我们会抛出一个错误。否则,我们将结果
设置为传递给函数的初始
值。其他一切正常。
注解1:我们不修改initial
(即写initial = array[index++]
)的原因是因为如果我们使用函数中的参数
并修改函数的参数,则函数将 not be optimized在V8中。因此,它的执行速度会变慢。
希望这有帮助。
关于javascript - 化简函数采用未定义的初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28654202/