【问题标题】:Reduce function to take an undefined initial value减少函数以获取未定义的初始值
【发布时间】:2015-02-22 03:33:56
【问题描述】:

我想创建一个执行以下操作的函数(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

如果initialundefined

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 )。

【问题讨论】:

  • 如果数组长度为 4(比如[1,2,3,1])并且initial 设置为 1,会发生什么?
  • 你为什么不看一下lodash的reduce代码?
  • @aduch 它会是:1+1;总计 = 2 2+2;总计 = 4 4+3;总计 = 7 7+1;总计 = 8
  • @thefourtheye 我意识到有一种方法,但这只是我正在经历的一个学习过程,我被困住了......所以如果有人可以帮助我,那就太好了
  • @HenryNg 只需将collection 中的第一个值分配给total,然后继续处理第二个元素。

标签: javascript function lodash


【解决方案1】:

这就是我将如何实现它:

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 是空的,那么我们会抛出一个错误。否则,我们将result 设置为传递给函数的initial 值。其他一切正常。

注1:我们之所以不修改initial(即写initial = array[index++])是因为如果我们在函数中使用arguments,同时修改函数的参数,那么该函数将在 V8 中为not be optimized。因此,它会执行得更慢。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    • 2012-03-24
    • 2020-06-14
    • 2021-08-10
    • 2016-07-31
    相关资源
    最近更新 更多