我需要在JavaScript开关语句的多个情况下,类似于:
switch (varName)
{
case "afshin", "saeed", "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
我该怎么做呢?如果在JavaScript中没有办法做这样的事情,我想知道一个也遵循DRY概念的替代解决方案。
我需要在JavaScript开关语句的多个情况下,类似于:
switch (varName)
{
case "afshin", "saeed", "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
我该怎么做呢?如果在JavaScript中没有办法做这样的事情,我想知道一个也遵循DRY概念的替代解决方案。
当前回答
下面是另一个易于使用的开关case语句。可以满足您的要求。我们可以在switch语句中使用find方法来获得所需的输出。
switch(varname){
case["afshin","saeed","larry"].find(name => name === varname):
alert("Hey")
break;
default:
alert('Default case');
break;
}
其他回答
更干净的处理方法
if (["triangle", "circle", "rectangle"].indexOf(base.type) > -1)
{
//Do something
}else if (["areaMap", "irregular", "oval"].indexOf(base.type) > -1)
{
//Do another thing
}
您可以为具有相同结果的多个值执行此操作
我是这样使用的:
switch (true){
case /Pressure/.test(sensor):
{
console.log('Its pressure!');
break;
}
case /Temperature/.test(sensor):
{
console.log('Its temperature!');
break;
}
}
你可以使用'in'操作符… 它依赖于对象/散列调用,所以它的速度和JavaScript一样快。
// Assuming you have defined functions f(), g(a) and h(a,b)
// somewhere in your code,
// you can define them inside the object, but...
// the code becomes hard to read. I prefer it this way.
o = { f1:f, f2:g, f3:h };
// If you use "STATIC" code can do:
o['f3']( p1, p2 )
// If your code is someway "DYNAMIC", to prevent false invocations
// m brings the function/method to be invoked (f1, f2, f3)
// and you can rely on arguments[] to solve any parameter problems.
if ( m in o ) o[m]()
其中一个可能的解决方案是:
const names = {
afshin: 'afshin',
saeed: 'saeed',
larry: 'larry'
};
switch (varName) {
case names[varName]: {
alert('Hey');
break;
}
default: {
alert('Default case');
break;
}
}
你可以这样写:
switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}