JavaScript,Typescript switch语句:两种情况下运行相同代码的方式? [英] JavaScript, Typescript switch statement: way to run same code for two cases?

查看:42
本文介绍了JavaScript,Typescript switch语句:两种情况下运行相同代码的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不复制和粘贴的情况下将两个不同的case值分配给同一代码块?例如,下面的68和40应该执行相同的代码,而下面的30不相关.

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;

推荐答案

只要将它们紧紧地放在一起就可以了

Just put them right after each other without a break

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

  case 30:
    // Do stuff
  break;
}

这篇关于JavaScript,Typescript switch语句:两种情况下运行相同代码的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆