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

如何在指定条件触发时返回if语句中成立的条件总数量?

实现方案

你可以把所有需要校验的独立条件单独提取为布尔值数组,直接统计数组中true的个数即可,这种方式逻辑清晰,后续新增/删除条件只需要修改数组内容就行。

通用逻辑

  • 把每个判断条件的计算结果单独作为数组的一项,结果为true代表条件成立,false代表不成立
  • 统计数组内true的总数量,即为满足条件的个数

代码示例

以JavaScript为例:

function getMetConditionCount() {
  // 单独定义所有校验条件
  const conditionList = [
    a > b,
    a < c,
    d == e,
    f == e
  ]
  // 过滤出所有成立的条件,返回数量
  return conditionList.filter(Boolean).length
}

如果使用Python,实现更简单,布尔值在数值计算中True等价于1,False等价于0,直接求和即可:

def get_met_condition_count():
    condition_list = [
        a > b,
        a < c,
        d == e,
        f == e
    ]
    return sum(condition_list)

如果你的原逻辑要求至少有一个条件成立时才返回数量,加一层判断即可,示例:

function yourBusinessFunction() {
  const conditionList = [
    a > b,
    a < c,
    d == e,
    f == e
  ]
  const metCount = conditionList.filter(Boolean).length
  if (metCount > 0) {
    return metCount
  }
  // 此处补充无满足条件时的其他业务逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 16:15:04