【问题标题】:Accumulator returns NaN in reduce function in Javascript累加器在Javascript的reduce函数中返回NaN
【发布时间】:2018-11-21 07:04:52
【问题描述】:

我正在学习使用扩展运算符... 编写一个函数,该函数接受传递给函数的所有参数并返回偶数之和。我的问题是为什么我的 acc 等于 NaN 除了 reduce() 的第一个回调?

代码和执行的打印输出如下,console.log(...)是我插入的调试代码。感谢您的帮助。

function sumEvenArgs(...args){
      var sum = args.reduce( (acc, next) => {
        console.log("\nnext:", next);
        if (next % 2 === 0) {
          acc += next;
          console.log("in if - acc:", acc);
        } else {
          acc += 0;
          console.log("in else - acc:", acc);
        }
      }, 0);

      return sum;
    }
    var sum = sumEven(1,2,3,4) // 6
    console.log("sum:", sum);

输出

next: 1
in else - acc: 0

next: 2
in if - acc: NaN

next: 3
in else - acc: NaN

next: 4
in if - acc: NaN
sum: undefined

【问题讨论】:

  • 您不会在每个循环结束时返回 acc

标签: javascript higher-order-functions


【解决方案1】:

你应该在你的回调函数结束时返回 acc

function sumEvenArgs(...args){
    var sum = args.reduce( (acc, next) => {
        console.log("\nnext:", next);
        if (next % 2 === 0) {
            acc += next;
            console.log("in if - acc:", acc);
        } else {
            acc += 0;
            console.log("in else - acc:", acc);
        }
        return acc ; // you need to add this line 
    }, 0);

    return sum;
}
var sum = sumEvenArgs(1,2,3,4) // 6
console.log("sum:", sum);

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 2021-06-28
    • 2017-06-12
    • 2019-10-20
    • 2016-03-01
    相关资源
    最近更新 更多