首页 > 解决方案 > reduce() 有问题;

问题描述

我不太了解 .reduce() 方法

我已经尝试对代码进行一些修改,我可以看到累加器在第一种情况下增加,但随后在后续迭代中变为“未定义”和“NaN”。不确定为什么当 val.voted === true 时值没有累积。

function totalVotes(arr) {
  return arr.reduce((acc, val) => { val.voted === true ? acc+=1 : acc;}, 0); 

}

var voters = [
    {name:'Bob' , age: 30, voted: true},
    {name:'Jake' , age: 32, voted: true},
    {name:'Kate' , age: 25, voted: false},
    {name:'Sam' , age: 20, voted: false},
    {name:'Phil' , age: 21, voted: true},
    {name:'Ed' , age:55, voted:true},
    {name:'Tami' , age: 54, voted:true},
    {name: 'Mary', age: 31, voted: false},
    {name: 'Becky', age: 43, voted: false},
    {name: 'Joey', age: 41, voted: true},
    {name: 'Jeff', age: 30, voted: true},
    {name: 'Zack', age: 19, voted: false}
];
console.log(totalVotes(voters)); // 7

结果应该是 7..

标签: javascriptarrays

解决方案


Your callback function must return a value for the accumulator during the next iteration. Currently, you don't have a return, so execution falls through and returns undefined on the first call. To fix this, simply add return:

function totalVotes(arr) {
  return arr.reduce((acc, val) => { return val.voted === true ? acc+=1 : acc;}, 0); 

}

Alternatively, you can remove the braces, since you are using fat arrow syntax:

function totalVotes(arr) {
  return arr.reduce((acc, val) => val.voted === true ? acc+=1 : acc, 0); 

}

推荐阅读