简体   繁体   English

累加器在Javascript的reduce函数中返回NaN

[英]Accumulator returns NaN in reduce function in Javascript

I am learning to use ... , the spread operator, to write a function that takes all the parameters passed to a function and returns the sum of the even ones.我正在学习使用... ,展开运算符,编写一个函数,该函数接受传递给函数的所有参数并返回偶数的总和。 My question is that why my acc equal to NaN except the first callback of reduce()?我的问题是为什么我的 acc 等于 NaN,除了 reduce() 的第一个回调?

The code and the executed print-out are below, and console.log(...) are the debugging code I inserted.代码和执行的打印输出如下, console.log(...)是我插入的调试代码。 Thank you for your help.感谢您的帮助。

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

Output :输出

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

you should return acc at the end of your callback function您应该在回调函数结束时返回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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM