javascript新手,我无法计算 bool(boolean) 值数组中的true数。我正在尝试使用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
最佳答案
看来您的问题已经解决了,但是有很多更简单的方法可以解决。
.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);