我需要在JavaScript开关语句的多个情况下,类似于:

switch (varName)
{
   case "afshin", "saeed", "larry":
       alert('Hey');
       break;

   default:
       alert('Default case');
       break;
}

我该怎么做呢?如果在JavaScript中没有办法做这样的事情,我想知道一个也遵循DRY概念的替代解决方案。


当前回答

在Node.js中,你可以这样做:

data = "10";
switch(data){
    case "1": case "2": case "3": // Put multiple cases on the same
                                  // line to save vertical space.
        console.log("small");
        break;

    case "10": case "11": case "12":
        console.log("large");
        break;

    default:
        console.log("strange");
        break;
}

这使得代码在某些情况下更加紧凑。

其他回答

下面是完全避免switch语句的不同方法:

var cases = {
  afshin: function() { alert('hey'); },
  _default: function() { alert('default'); }
};
cases.larry = cases.saeed = cases.afshin;

cases[ varName ] ? cases[ varName ]() : cases._default();

我是这样使用的:

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]()

如果您的case条件很复杂,需要很多case值匹配,或者需要动态值匹配,那么最好将case匹配逻辑移动到处理程序子函数中。

在您的情况下,如果您有成千上万的用户名来匹配安全权限检查,这种方法是更清晰的选项,更可扩展,可以暴露高级多路分支逻辑,而不会陷入一长串case语句中。


    switch (varName)
    {     
      case checkPatternAdministrator(varName):
        alert('Hey');
        break;

      case checkPatternUserTypeA(varName):
        alert('Hey2');
        break;

      case checkPatternUserTypeB(varName):
        alert('Hey3');
        break;

      default:
        alert('Default case');
        break;
    }
 function checkPatternAdministrator(varName) {
    // Logic to check Names against list, account permissions etc.
    // return the varName if a match is found, or blank string if not
    var matchedAdministratorName = varName;

    return matchedAdministratorName;
  }

我的情况类似于:

switch (text) {
  case SOME_CONSTANT || ANOTHER_CONSTANT:
    console.log('Case 1 entered');

  break;

  case THIRD_CONSTANT || FINAL_CONSTANT:
    console.log('Case 2 entered');

  break;

  default:
    console.log('Default entered');
}

总是输入默认大小写。如果你遇到了类似的多例switch语句问题,你要找的是:

switch (text) {
  case SOME_CONSTANT:
  case ANOTHER_CONSTANT:
    console.log('Case 1 entered');

  break;

  case THIRD_CONSTANT:
  case FINAL_CONSTANT:
    console.log('Case 2 entered');

  break;

  default:
    console.log('Default entered');
}