【问题标题】:Reduce in javascript with initial value用初始值减少javascript
【发布时间】:2021-03-27 07:31:01
【问题描述】:

我正在尝试将数组减少为其偶数值的总和。我一直在查看 MDN 的文档 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

这表示如果提供了初始值,那么它不会跳过第 0 个索引,实际上它将从索引 0 开始。我的问题是 reduce 从索引 1 开始。因此,我的结果不正确。我确定我阅读文件不正确或误解了它。这是我指的注释 - \"注意:如果没有提供initialValue,reduce()将从索引1开始执行回调函数,跳过第一个索引。如果提供了initialValue,它将从索引0开始。\ "

这是我的代码。

var array = [1,2,3,4,6,100];
var initialValue = 0;
var value = array.reduce(function(accumulator, currentValue, currentIndex, array, initialValue) {
    //console.log(accumulator);
    if( currentValue % 2 === 0) {
      accumulator += currentValue;
      //return accumulator;
    }
    return accumulator;
});
console.log(value);

显然,我看到的结果是 113 而不是 112。我猜,这是因为 accumulator 已经有一个值 1。因此,它最初是加 1。

    标签: javascript


    【解决方案1】:

    如果你再看一下文档,你会注意到callbackFn最多只取4个变量,而initialValue必须在第二个参数上

    arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])
                       ^                                               ^
    

    这是按预期返回112 的小修复版本

    var array = [1,2,3,4,6,100];
    var initialValue = 0;
    var value = array.reduce(function(accumulator, currentValue, currentIndex, array) {
        //console.log(accumulator);
        if( currentValue % 2 === 0) {
          accumulator += currentValue;
          //return accumulator;
        }
        return accumulator;
    }, initialValue);
    console.log(value);

    【讨论】:

      【解决方案2】:

      这是 MDN 提供的使用初始值的语法:

       [0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
          return accumulator + currentValue}, 10)
      

      这个例子中的初始值是 10,它应该作为第二个参数传递给 reduce 函数。

      【讨论】:

        【解决方案3】:

        您没有将初始值参数传递给 reduce 函数。

        喜欢@hgb123解释一下,它是第二个参数。

        此外,如果您不需要它们,则不需要传递所有参数。让你的函数尽可能简单,这样它们会更容易阅读:

        var array = [1,2,3,4,6,100];
        
        var value = array.reduce(function(accumulator, currentValue) {
            //console.log(accumulator);
            if( currentValue % 2 === 0) {
              accumulator += currentValue;
              //return accumulator;
            }
            return accumulator;
        }, 0);
        
        console.log(value);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-11-10
          • 2022-06-13
          • 2021-09-16
          • 1970-01-01
          • 2013-01-25
          • 1970-01-01
          • 1970-01-01
          • 2016-11-01
          相关资源
          最近更新 更多