Javascript switch 语句:有没有办法让两种情况运行相同的代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7559531/
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
Javascript switch statement: Is there a way for two cases to run the same code?
提问by nipponese
Is there a way to assign two different case values to the same block of code without copy and pasting? For example, below 68 and 40 should execute the same code, while 30 is not related.
有没有办法在不复制和粘贴的情况下将两个不同的 case 值分配给同一个代码块?比如68以下和40应该执行相同的代码,而30是不相关的。
case 68:
//Do something
break;
case 40:
//Do the same thing
break;
case 30:
//Do something different
break;
Is it incorrect to think something like this should work (even though it obviously doesn't)?
认为这样的事情应该有效(即使显然无效)是否不正确?
case 68 || 40:
//Do something
break;
case 30:
//Do something else
break;
回答by klaustopher
Just put them right after each other without a break
只需将它们紧随其后,不间断
switch (myVar) {
case 68:
case 40:
// Do stuff
break;
case 30:
// Do stuff
break;
}
回答by RichieHindle
Yes, you just put the related case
statements next to each other, like this:
是的,您只需将相关case
语句放在一起,如下所示:
case 40: // Fallthrough
case 68:
// Do something
break;
case 30:
// Do something different
break;
The Fallthrough
comment is there for two reasons:
有Fallthrough
评论有两个原因:
- It reassures human readers that you're doing this deliberately
- It silences warnings from Lint-like tools that issue warnings about possible accidental fallthrough.
- 它让人类读者放心,你是故意这样做的
- 它消除了来自类似 Lint 的工具的警告,这些工具会发出有关可能的意外失败的警告。
回答by BNL
case 68:
case 40:
// stuff
break;
回答by RkHirpara
Switch cases can be clubbed as shown in the dig.
Also, It is not limited to just two cases, you can extend it to any no. of cases.
此外,它不仅限于两种情况,您可以将其扩展到任何没有。的情况。
回答by SimranChahal
You should use:
你应该使用:
switch condition {
case 1,2,3:
// do something
case 4,5:
// do something
default:
// do something
}
Cases should be comma-separated.
大小写应以逗号分隔。