[英]Can someone explain why this reduce method return like this?
I have an array of object 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}
];
I used reduce to count number of people who voted:我用 reduce 来计算投票的人数:
function totalVotes(arr) {
return arr.reduce(function voteCount(acc,cur){
return acc+cur.voted;
},0)
}
The function return correct answer which make me confuse. function 返回正确答案,这让我感到困惑。 It doesn't has any condition to check whether that person is voted or not so how can it return the right answer?
它没有任何条件来检查那个人是否被投票,那么它如何返回正确的答案?
By doing acc+cur.voted
you implicitly cast the boolean cur.voted
to a number (false -> 0, true -> 1).通过执行
acc+cur.voted
您可以将 boolean cur.voted
隐式转换为一个数字(false -> 0,true -> 1)。 Therefore by "adding up" those booleans, you'll receive the count of booleans being true
:因此,通过“加起来”这些布尔值,您将收到布尔
true
的计数:
console.log( true + false, true + true );
Javascript has a dynamic type system that uses type coercion . Javascript 具有使用类型强制的动态类型系统。 When you have an expression with a two variables where one is an integer and the is boolean type coercion happens.
当您有一个包含两个变量的表达式时,其中一个是 integer 并且是 boolean 类型强制发生。 The bool value will be interpreted as 1 or 0. Try this in an interactive JS (eg node, repl.it):
bool 值将被解释为 1 或 0。在交互式 JS(例如 node、repl.it)中试试这个:
0 + true
it returns 1
.它返回
1
。
In your reduce callback function you start with an initial value of 0 for the accumulator acc
.在您的减少回调 function 中,您从累加器
acc
的初始值 0 开始。 Then you add the boolean values cur.voted
to it.然后将 boolean 值
cur.voted
添加到它。 This will return acc + 1
for a list element with voted = true
and acc
for a list element with voted = false
.这将为带有
voted = true
的列表元素返回acc
acc + 1
,对于带有voted = false
的列表元素返回 acc 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.