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

后端 未结 4 1522
傲寒
傲寒 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:32

    You should use ++a instead a++ because you have to change the value of a suddenly. a variable will be incremented after its value is returned.

     myCount = [false,false,true,false,true].reduce(function(a,b){
          return b? ++a:a;
        },0);
    alert("myCount ="+ myCount); 

提交回复
热议问题