Javascript 计算不带“.reduce()”、“.filter()”`forEach()的True/False数`
有没有办法知道一个数组中有多少个“True”? 但不使用Javascript 计算不带“.reduce()”、“.filter()”`forEach()的True/False数`,javascript,arrays,count,Javascript,Arrays,Count,有没有办法知道一个数组中有多少个“True”? 但不使用.reduce(),.filter()forEach(): 如果只有true/false元素,我想您可以。加入,然后用正则表达式检查字符串中有多少trues: const getTrueCount=array=>(array.join().match(/true/g)| |[])长度; log(getTrueCount([true,false,true,false])最简单的解决方案是将布尔值转换为数字(true=>1, false=>
.reduce()
,.filter()
forEach()
:
如果只有
true
/false
元素,我想您可以。加入,然后用正则表达式检查字符串中有多少true
s:
const getTrueCount=array=>(array.join().match(/true/g)| |[])长度;
log(getTrueCount([true,false,true,false])代码>最简单的解决方案是将布尔值转换为数字(true=>1,
false=>0)。操作数之前的一元+用于此操作:
var x = [true,false,true,false]
const数组=[true,false,true,false];
函数getTrueCount(数组){
让trueCount=0;
for(设i=0;i
函数方法是递归执行,它不使用循环和数组方法:
const countTrue=([x,…r])=>(+x | | 0)+(r.length?countTrue(r):0);
log(countTrue([true,false,true,false]);
log(countTrue([false,false,true,false]);
log(countTrue([false,false,false,false]);
console.log(countTrue([])你能解释一下限制吗?您可以使用一些
或每个
吗?如果对相当明显的用例有限制,那么可以帮助解释为什么会有这些限制。那么循环有什么问题呢?不确定select应该是什么。@Ryul,您可以编写一个递归函数来实现它
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;
}