javascript - 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..
解决方案
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);
}
推荐阅读
- php - 从 Rest API 获取 JSON 数据
- json - POSTMAN - 从 JSON 响应中保存属性值
- docker-compose - 如何在不重新启动所有服务的情况下将新端口添加到 docker-compose 服务之一?
- laravel - Laravel 资源 API CURL | 存储/删除不起作用
- php - Wordpress - 使用 ACP 的给定页面的 CPT 子级
- javascript - 使用 react 调试 webpack 配置
- c# - 读取嵌套的大括号作为字符串的一部分
- ios - Swift动态tableview高度
- c# - 如果使用“Any Cpu”配置构建,应用程序将在 64 位窗口上使用哪个 .net 框架(32 位或 64 位)
- bash - 将文本写入 bash 脚本中的文件,使用变量替换但没有反引号替换