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

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

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

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


当前回答

只需改变开关条件方法:

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

其他回答

我是这样使用的:

switch (true){
     case /Pressure/.test(sensor): 
     {
        console.log('Its pressure!');
        break;
     }

     case /Temperature/.test(sensor): 
     {
        console.log('Its temperature!');
        break;
     }
}

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

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

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

如果您的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语句的直通特性。匹配的case会一直运行,直到找到break(或者switch语句的结尾),所以你可以这样写:

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

   default: 
       alert('Default case');
}
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Example1</title>
    <link rel="stylesheet" href="css/style.css" >
    <script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
    <script>
        function display_case(){
            var num =   document.getElementById('number').value;

                switch(num){

                    case (num = "1"):
                    document.getElementById("result").innerHTML = "You select day Sunday";
                    break;

                    case (num = "2"):
                    document.getElementById("result").innerHTML = "You select day  Monday";
                    break;

                    case (num = "3"):
                    document.getElementById("result").innerHTML = "You select day  Tuesday";
                    break;

                    case (num = "4"):
                    document.getElementById("result").innerHTML = "You select day  Wednesday";
                    break;

                    case (num = "5"):
                    document.getElementById("result").innerHTML = "You select day  Thusday";
                    break;

                    case (num = "6"):
                    document.getElementById("result").innerHTML = "You select day  Friday";
                    break;

                    case (num = "7"):
                    document.getElementById("result").innerHTML = "You select day  Saturday";
                    break;

                    default:
                    document.getElementById("result").innerHTML = "You select day  Invalid Weekday";
                    break
                }

        }
    </script>
</head>
<body>
    <center>
        <div id="error"></div>
        <center>
            <h2> Switch Case Example </h2>
            <p>Enter a Number Between 1 to 7</p>
            <input type="text" id="number" />
            <button onclick="display_case();">Check</button><br />
            <div id="result"><b></b></div>
        </center>
    </center>
</body>