计算布尔值数组中真实成员的数量 [英] Count the number of true members in an array of boolean values

查看:80
本文介绍了计算布尔值数组中真实成员的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript的新手,我无法计算布尔值数组中的true数.我正在尝试使用reduce()函数.有人可以告诉我我在做什么错吗?

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'm doing wrong?

   //trying to count the number of true in an array
    myCount = [false,false,true,false,true].reduce(function(a,b){
      return b?a++:a;
    },0);
    alert("myCount ="+ myCount);  // this is always 0

推荐答案

似乎您的问题已经解决,但是有很多更简单的方法可以解决.

Seems like your problem is solved already, but there are plenty of easier methods to do it.

Array.prototype.filter() -我认为最简单的一种.

Array.prototype.filter() - the easiest one, in my opinion.

console.log([true,false,true,false,true].filter(v => v).length);

甚至更简单:

console.log([true,false,true,false,true].filter(Boolean).length);

Array.prototype.forEach()

Array.prototype.forEach()

var myCounter = 0;

[true,false,true,false,true].forEach(v => v ? myCounter++ : v);

console.log(myCounter);

这篇关于计算布尔值数组中真实成员的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆