JavaScript中多个case的switch语句
我需要在 JavaScript 中的 switch 语句中使用多个案例,例如:
I need multiple cases in switch statement in JavaScript, Something like:
switch (varName)
{
case "afshin", "saeed", "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
我该怎么做?如果没有办法在 JavaScript 中做类似的事情,我想知道一个替代解决方案,它也遵循 DRY 概念.
How can I do that? If there's no way to do something like that in JavaScript, I want to know an alternative solution that also follows the DRY concept.
推荐答案
使用 switch
语句的贯穿功能.匹配的 case 将一直运行,直到找到 break
(或 switch
语句的结尾),所以你可以这样写:
Use the fall-through feature of the switch
statement. A matched case will run until a break
(or the end of the switch
statement) is found, so you could write it like:
switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;
default:
alert('Default case');
}
相关文章