JavaScript,类型转换语句: 两种情况下运行相同代码的方法?

有没有一种方法可以将两个不同的 case 值分配给同一块代码,而不需要复制和粘贴?例如,低于68和40应该执行相同的代码,而30是不相关的。

case 68:
//Do something
break;


case 40:
//Do the same thing
break;


case 30:
//Do something different
break;

认为这样的东西应该起作用(即使它显然不起作用)是不正确的吗?

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


case 30:
//Do something else
break;
58415 次浏览
case 68:
case 40:
// 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.

Just put them right after each other without a break

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


case 30:
// Do stuff
break;
}

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.

You should use:

switch condition {
case 1,2,3:
// do something
case 4,5:
// do something
default:
// do something
}

Cases should be comma-separated.

Cleaner way to do that 👌

if ([68, 48, 22, 53].indexOf(value) > -1)
//Do something
else if ([44, 1, 0, 24, 22].indexOf(value) > -1)
//Do another

You can do that for multiple values with the same result