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

如何重构带有重复条件判断的if代码块?

简化递进式条件判断的重构方案

原始代码

if(a && b && c && d && e && f)
  return 5;
if(b && c && d && e && f)
  return 4;
if(c && d && e && f)
  return 3;
if(d && e && f)
  return 2;
if(e && f)
  return 1;
if (f)
  return 0;
return -1;

你的优化尝试

let res = -1;
if(f) {
  res = 0;
  if(e) {
    res = 1;
    if(d) {
      res = 2;
      if(c) {
        res = 3;
      } if(b) {
        res = 4;
        if(a) {
          res = 5;
        }
      }
    }
  }
}
return res;

更简洁的无冗余重构方式

方案1:数组映射遍历

把条件和对应返回值按优先级(从高到低)存入数组,遍历找到第一个满足条件的项返回,逻辑清晰且易于扩展:

const conditions = [
  { check: () => a && b && c && d && e && f, value: 5 },
  { check: () => b && c && d && e && f, value: 4 },
  { check: () => c && d && e && f, value: 3 },
  { check: () => d && e && f, value: 2 },
  { check: () => e && f, value: 1 },
  { check: () => f, value: 0 },
];

for (const cond of conditions) {
  if (cond.check()) return cond.value;
}
return -1;

方案2:精简嵌套累加判断

从最基础的条件开始,逐步叠加前置条件,每满足一个就更新返回值,完全消除冗余判断,代码紧凑且可读性好:

let result = -1;
if (f) {
  result = 0;
  if (e) {
    result = 1;
    if (d) {
      result = 2;
      if (c) result = 3;
      if (b) result = a ? 5 : 4;
    }
  }
}
return result;

方案3:权重计算式判断

给每个条件赋予对应权重,按顺序检查后直接计算结果,逻辑简洁高效:

let res = -1;
if (f) {
  res = 0;
  if (e) res += 1;
  if (d) res += 1;
  // 处理特殊权重的b和a
  if (b) {
    res = a ? 5 : 4;
  } else if (c) {
    res = 3;
  }
}
return res;

最推荐方案1,可维护性最高——后续增减条件或调整返回值,只需修改数组内容,无需改动核心逻辑;如果追求代码极致简洁且条件固定,方案2的写法已经足够清晰直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:43:27