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

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

问题描述

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

//尝试计算数组中true的个数myCount = [false,false,true,false,true].reduce(function(a,b){返回 b?a++:a;},0);alert("myCount ="+ myCount);//这总是 0

解决方案

看起来你的问题已经解决了,但还有很多更简单的方法可以解决.

<块引用>

优秀之一:

.filter(Boolean);//将每个真值保存在一个数组中

const arr = [true, false, true, false, true];const count = arr.filter(Boolean).length;console.log(count);

好的一个:

const arr = [true, false, true, false, true];const count = arr.filter((value) => value).length;console.log(count);

平均替代:

让 myCounter = 0;[真、假、真、假、真].forEach(v => v ? myCounter++ : v);console.log(myCounter);

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.

Excellent one:

.filter(Boolean); // will keep every truthy value in an array

const arr = [true, false, true, false, true];
const count = arr.filter(Boolean).length;

console.log(count);

Good one:

const arr = [true, false, true, false, true];
const count = arr.filter((value) => value).length;

console.log(count);

Average alternative:

let myCounter = 0;

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

console.log(myCounter);

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

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