简体   繁体   中英

Can someone explain why this reduce method return like this?

I have an array of object like this:

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:

function totalVotes(arr) {
    return arr.reduce(function voteCount(acc,cur){
        return acc+cur.voted;
    },0)
}

The function return correct answer which make me confuse. 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). Therefore by "adding up" those booleans, you'll receive the count of booleans being true :

 console.log( true + false, true + true );

Javascript has a dynamic type system that uses type coercion . When you have an expression with a two variables where one is an integer and the is boolean type coercion happens. The bool value will be interpreted as 1 or 0. Try this in an interactive JS (eg node, repl.it):

0 + true

it returns 1 .

In your reduce callback function you start with an initial value of 0 for the accumulator acc . Then you add the boolean values cur.voted to it. This will return acc + 1 for a list element with voted = true and acc for a list element with voted = false .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM