You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取JavaScript列表中值为False的元素数量?

统计列表中False元素的数量

以下是几种实用的实现方式:

  • 使用filter()结合length属性:

    const myList = [true, false, false];
    const falseCount = myList.filter(item => item === false).length;
    console.log(falseCount); // 输出 2
    

    filter()会筛选出所有值为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 13:45:32