[英]Accumulator returns NaN in reduce function in Javascript
我正在學習使用...
,展開運算符,編寫一個函數,該函數接受傳遞給函數的所有參數並返回偶數的總和。 我的問題是為什么我的 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
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.