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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:44:00  来源:igfitidea点击:

Javascript switch statement: Is there a way for two cases to run the same code?

javascriptswitch-statement

提问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 casestatements next to each other, like this:

是的,您只需将相关case语句放在一起,如下所示:

case 40:  // Fallthrough
case 68:
   // Do something
   break;

case 30:
   // Do something different
   break;

The Fallthroughcomment 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.

大小写应以逗号分隔。