如何优化嵌套if

How to optimize nested if?

本文关键字:嵌套 if 优化 何优化      更新时间:2023-09-26

嗨,我想知道有更好的方法吗?条件a比b更重要,b比c更重要,等等。

var slot = condition_a
if (!slot) {
  slot = condition_b
  if (!slot) {
    slot = condition_c
    if (!slot) {
      slot = condition_d
      if (!slot) {
        slot = condition_e
      }
    }
  }
}
if (slot) {
  //do something
}

您执行OR:

if (condition_a || condition_b || condition_c || condition_d || condition_e) {
      // do something
}

这相当于您的代码。如果条件评估为true,则不检查以下条件(称为短路评估)。它可以进行这样的检查:

if (a===null || a.b===0) {

请注意,在同一个地方有这么多条件看起来像一种代码气味:可能有一些东西在语义上设计得不够。

您也可以像这样使用||条件,

slot = condition_a||condition_b||condition_c||condition_d;

Fiddle 示例

如果您需要slot有一个值(而不仅仅是在最后使用它来测试条件)

var slot = condition_a || condition_b || condition_c || condition_d || condition_e;
if (slot) {
  // do soemthing
}