var x = [true,false,true,false]
有没有办法告诉阵列中有多少“真”?但是没有使用.reduce()
,.filter()
forEach()
:
How to get the count of boolean value (if it is true) in array of objects
Count the number of true members in an array of boolean values
最简单的解决方案是使用cast boolean来编号(true => 1,false => 0)。操作数之前的一元+用于此操作:
const array = [true, false, true, false];
function getTrueCount(array) {
let trueCount = 0;
for (let i = 0; i < array.length; i++) {
trueCount += +(array[i]);
}
return trueCount;
}
如果只有true
/ false
元素,我想你可以.join
,然后用正则表达式检查字符串中有多少true
s:
const getTrueCount = array => (array.join().match(/true/g) || []).length;
console.log(getTrueCount([true,false,true,false]));
一种功能性的方法是递归地执行它,它不使用循环而不使用数组方法:
const countTrue = ([x, ...r]) => (+x || 0) + (r.length ? countTrue(r) : 0);
console.log(countTrue([true,false,true,false]));
console.log(countTrue([false,false,true,false]));
console.log(countTrue([false,false,false,false]));
console.log(countTrue([]));