![](/img/trans.png)
[英]Can someone explain to me why this syntax using parentheses instead of curly brackets, adding comma and no more “return” in reduce method?
[英]Can someone explain why this reduce method return like this?
我有一个 object 数组,如下所示:
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}
];
我用 reduce 来计算投票的人数:
function totalVotes(arr) {
return arr.reduce(function voteCount(acc,cur){
return acc+cur.voted;
},0)
}
function 返回正确答案,这让我感到困惑。 它没有任何条件来检查那个人是否被投票,那么它如何返回正确的答案?
通过执行acc+cur.voted
您可以将 boolean cur.voted
隐式转换为一个数字(false -> 0,true -> 1)。 因此,通过“加起来”这些布尔值,您将收到布尔true
的计数:
console.log( true + false, true + true );
Javascript 具有使用类型强制的动态类型系统。 当您有一个包含两个变量的表达式时,其中一个是 integer 并且是 boolean 类型强制发生。 bool 值将被解释为 1 或 0。在交互式 JS(例如 node、repl.it)中试试这个:
0 + true
它返回1
。
在您的减少回调 function 中,您从累加器acc
的初始值 0 开始。 然后将 boolean 值cur.voted
添加到它。 这将为带有voted = true
的列表元素返回acc
acc + 1
,对于带有voted = false
的列表元素返回 acc 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.