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

如何统计JavaScript数组中真值(truth value)的数量

布尔数组真值统计方案

以下是三种可直接落地的实现方式:

  • 极简一行写法
    用filter过滤目标项后直接取长度即可:
    // 仅统计严格等于布尔true的项
    const trueCount = checkedState.filter(item => item === true).length
    // 若接受所有隐式为真的值(如1、非空字符串等),可以简化为
    // const trueCount = checkedState.filter(Boolean).length
    setCourseProgress(trueCount)
    
  • reduce迭代写法
    遍历过程直接累加计数,性能略优:
    const trueCount = checkedState.reduce((count, cur) => count + (cur === true ? 1 : 0), 0)
    setCourseProgress(trueCount)
    
  • 原有forEach逻辑修正版
    你原来的代码缺少计数变量,补充后即可正常运行:
    const checkedState = [true, false, true]
    
    function handleCourseProgress() {
      let count = 0
      checkedState.forEach((value) => {
        if (value === true) {
          count++
        }
      })
      setCourseProgress(count);
    }
    

提示:如果确定数组里只有布尔值,可以省略=== true的严格判断,直接判断值本身即可。

内容的提问来源于stack exchange,提问作者lache

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 16:45:00