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

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

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

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


当前回答

一些有趣的方法。对我来说,最好的解决方法是使用。find。

通过在find函数中使用合适的名称,可以指示多个情况是什么。

switch (varName)
{
   case ["afshin", "saeed", "larry"].find(firstName => firstName === varName):
       alert('Hey');
       break;

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

其他答案更适合给定的例子,但如果你有多种情况,对我来说,这是最好的方法。

其他回答

在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;
}

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

<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>

只需改变开关条件方法:

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

我喜欢它的清晰度和DRY语法。

varName = "larry";

switch (true)
{
    case ["afshin", "saeed", "larry"].includes(varName) :
       alert('Hey');
       break;

    default:
       alert('Default case');

}

如果您的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;
  }