简体   繁体   English

带有或条件的嵌套 if 语句

[英]Nested if statements with or condition

I have some js code that currently looks something like this:我有一些目前看起来像这样的 js 代码:

var test
//do some stuff with the var
if (test === "A" || test === "B" || test === "C") {
    if (test === "A" || test === "B") {
        //do some small stuff
    } 
    //do some more complex stuff
}

Is there a nicer way to write this to avoid the duplicated condition?有没有更好的方法来写这个以避免重复的情况? It seems basic, I know, but I can't quite put my finger on it.我知道,这似乎很基本,但我不能完全理解它。

you could assign a variable to avoid having to write the complex condition multiple times:您可以分配一个变量以避免多次编写复杂的条件:

let a_or_b = test === 'A' || test === 'B';
if (a_or_b || test === 'C') {
    if (a_or_b) {
        // do some small stuff
    }
    // do more complex stuff
}

or或者

let a_or_b = false;
if (test === 'A' || test === 'B') {
    // do some small stuff
    a_or_b = true;
}
if (a_or_b || test === 'C') {
    // do more complex stuff
}

My suggestion, just set the duplicated condition into as a variable, hope it help you我的建议,只需将重复的条件设置为变量,希望对您有所帮助

var test;
var isAOrB = (test === "A" || test === "B");
if (isAOrB || test === "C") {
if (isAOrB) {
    //do some small stuff
} 
//do some more complex stuff

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM