javascript 新手,我在计算 bool 值数组中真值的数量时遇到了问题。我正在尝试使用 reduce() 函数。谁能告诉我我做错了什么?
//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
最佳答案
看起来你的问题已经解决了,但是有很多更简单的方法可以做到这一点。
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);
好的:
const arr = [true, false, true, false, true];
const count = arr.filter((value) => value).length;
console.log(count);
平均选择:
let myCounter = 0;
[true, false, true, false, true].forEach(v => v ? myCounter++ : v);
console.log(myCounter);
关于javascript - 计算 bool 值数组中真实成员的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42317140/