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

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

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

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


当前回答

我的情况类似于:

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');
}

其他回答

只需改变开关条件方法:

switch (true) {
    case (function(){ return true; })():
        alert('true');
        break;
    case (function(){ return false; })():
        alert('false');
        break;
    default:
        alert('default');
}

其中一个可能的解决方案是:

const names = {
afshin: 'afshin',
saeed: 'saeed',
larry: 'larry'
};

switch (varName) {
   case names[varName]: {
       alert('Hey');
       break;
   }

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

添加并澄清Stefano的答案,您可以使用表达式动态地设置switch中的条件值,例如:

var i = 3
switch (i) {
    case ((i>=0 && i<=5) ? i : -1):
        console.log('0-5');
        break;

    case 6: console.log('6');
}

在你的问题中,你可以这样做:

var varName = "afshin"
switch (varName) {
    case (["afshin", "saeed", "larry"].indexOf(varName)+1 && varName):
      console.log("hey");
      break;

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

虽然很干…

你可以使用'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;
  }