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
Is it valid JavaScript to nest an if/else in a switch?
提问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 switch
and an if
in 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 switch
and an if
statement.
很抱歉恢复这样的旧帖子,但它可能会帮助来这里寻找如何组合或嵌套 aswitch
和if
语句的人。
回答by samehanwar
and you can also use ternary if
wrapped inside a return
statement
你也可以ternary if
在return
语句中使用wrapped
switch(foo) {
case 'bar':
return(
(raz == 'something') ?
// excute
:
// do something else
)
break;
...
default:
// yada yada
}