最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript, Typescript switch statement: way to run same code for two cases? - Stack Overflow

programmeradmin8浏览0评论

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:
   //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;

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:
   //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;
Share Improve this question edited Sep 16, 2020 at 9:34 HDJEMAI 9,80048 gold badges76 silver badges97 bronze badges asked Sep 26, 2011 at 18:28 rib3yerib3ye 2,9237 gold badges35 silver badges52 bronze badges 1
  • Does this answer your question? Switch statement for multiple cases in JavaScript – Ivar Commented Sep 9, 2021 at 12:02
Add a comment  | 

6 Answers 6

Reset to default 242

Just put them right after each other without a break

switch (myVar) {
  case 68:
  case 40:
    // Do stuff
  break;

  case 30:
    // Do stuff
  break;
}

Yes, you just put the related case statements next to each other, like this:

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

case 30:
   // Do something different
   break;

The Fallthrough comment is there for two reasons:

  • It reassures human readers that you're doing this deliberately
  • It silences warnings from Lint-like tools that issue warnings about possible accidental fallthrough.
case 68:
case 40:
  // stuff
  break;

Cleaner way to do that

发布评论

评论列表(0)

  1. 暂无评论