在 JavaScript 中跳出 if 块的正确方法?

Proper way to break out of an if block in JavaScript?

在 if 块结构中,如下所示,假设 condition_1 和 condition_2 互斥,但有时 condition_2 和后面的条件都为真;并且,当 condition_2 为真时,所需要做的就是跳出 if 块并继续执行其余代码,类似于 switch 语句。

除 condition_2 之外的所有条件都是 matches 用于具有多个按钮的父容器上的侦听器的语句。当 condition_2 为真时,它下面的按钮应该被禁用。

if ( condition_1 ) { }
else if ( condition_2 ) {  }
else if ( condition_3 ) {  }
else if ( condition_4 ) {  }
// ...
else if ( condition_n ) {  };   
// More code in the function before returning.

可以编码为:

if ( condition_1 ) { }
else if ( !condition_2 && condition_3 ) {  }
else if ( !condition_2 && condition_4 ) {  }
// ...
else if ( !condition_2 && condition_n ) {  };   
// More code in the function before returning.

if ( condition_1 ) { }
else if ( !condition_2 )
  {
    if ( condition_3 ) {  }
    else if ( condition_4 ) {  }
    // ...
    else if ( condition_n ) {  };   
  };
// More code in the function before returning.

是否只是 "bad" 编程习惯,只在第一个块中编写代码,而只是在 condition_2 的大括号之间不放置任何代码,这样当 condition_2 为真时,没有可执行的代码,但未测试其他条件,它会在 if 块末尾获取代码?

有没有更好更专业的方法来完成同样的事情?

我读到有关在 if 语句上放置 label 然后使用 break label,但我看不到添加的内容;并且有人提到 compiler/interpreter.

可能无法有效地使用该方法

谢谢。

如果条件是 true,您可以选择 labeled statement and break the block statement{}

var a = 2;
block: {
    if (a === 1) {
        console.log(1);
        break block;
    }
    if (a === 2) {
        console.log(2);
        break block;
    }
    if (a === 3) {
        console.log(3);
        break block;
    }
    console.log('end of block');
}

或者在同一作用域中使用另一个嵌套函数,return早点。

function check () {
    if (a === 1) {
        console.log(1);
        return;
    }
    if (a === 2) {
        console.log(2);
        return;
    }
    if (a === 3) {
        console.log(3);
        return;
    }
    console.log('end of function');
}

var a = 2;
check();