Javascript 在 switch 中嵌套 if/else 是否有效?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4926638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:48:42  来源:igfitidea点击:

Is it valid JavaScript to nest an if/else in a switch?

javascript

提问by Ben

Is this valid?

这是有效的吗?

switch(foo) {
    case 'bar':
    if(raz == 'something') {
        // execute
    } else {
        // do something else
    }
    break;
    ...
    default:
    // yada yada
}

回答by karim79

Yes, it is perfectly valid. Have you tried it?

是的,它完全有效。你试过吗?

回答by Jeffrey Roosendaal

You can combine a switchand an ifin a better way, if you really have to:

如果您真的必须这样做,您可以以更好的方式组合 aswitch和 an if

switch (true) {
    case (foo === 'bar' && raz === 'something'):
        // execute
        break;
    case (foo === 'bar'):
        // do something else
        break;
    default:
        // yada yada
}

Sorry to revive such an old post, but it may help people who came here looking how to combine or nest a switchand an ifstatement.

很抱歉恢复这样的旧帖子,但它可能会帮助来这里寻找如何组合或嵌套 aswitchif语句的人。

回答by samehanwar

and you can also use ternary ifwrapped inside a returnstatement

你也可以ternary ifreturn语句中使用wrapped

   switch(foo) {
        case 'bar':
          return(
            (raz == 'something') ? 
              // excute
            : 
              // do something else
          )
        break;
        ...
        default:
        // yada yada
    }