如何获取JavaScript列表中值为False的元素数量?
统计列表中False元素的数量
以下是几种实用的实现方式:
使用
filter()结合length属性:const myList = [true, false, false]; const falseCount = myList.filter(item => item === false).length; console.log(falseCount); // 输出 2filter()会筛选出所有值为false的元素并生成新数组,通过length即可获取该数组的元素数量,也就是目标统计数。使用
reduce()累加计数:const myList = [true, false, false]; const falseCount = myList.reduce((total, current) => { return current === false ? total + 1 : total; }, 0); console.log(falseCount); // 输出 2以0作为初始累加值,遍历列表时判断当前元素是否为
false,若是则将累加值加1,最终得到统计结果。使用for循环手动计数:
const myList = [true, false, false]; let falseCount = 0; for (const item of myList) { if (item === false) { falseCount++; } } console.log(falseCount); // 输出 2初始化计数器为0,遍历列表的每个元素,遇到
false就将计数器加1,遍历完成后得到总数。
内容的提问来源于stack exchange,提问作者JohnDole
相关产品推荐
相关产品推荐

