Count the number of true members in an array of boolean values

后端 未结 4 1520
傲寒
傲寒 2020-12-16 11:11

New to javascript and I\'m having trouble counting the number of trues in an array of boolean values. I\'m trying to use the reduce() function. Can someone tell me what I\

4条回答
  •  情歌与酒
    2020-12-16 11:52

    You're returning a++ when the value is true, which will always be zero. Post-increment happens after the value is retrieved. So on the first iteration, a is 0, and the value of a++ is also 0, even though a is incremented. Because a and b are parameters of the callback, it's a fresh a on each call.

    Instead:

    myCount = [true, false, true, false, true].reduce(function(a, b) {
      return b ? a + 1 : a;
    });
    
    console.log(myCount);

提交回复
热议问题