Switch statement multiple cases in JavaScript

2019-01-01 16:40发布

问题:

I need multiple cases in switch statement in JavaScript, Something like:

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

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

How can I do that? If there\'s no way to do something like that in JavaScript, I want to know an alternative solution that also follows DRY concept.

回答1:

Use the fall-through feature of the switch statement. A matched case will run until a break (or the end of the switch statement) is found, so you could write it like:

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

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


回答2:

This works in regular JavaScript

function theTest(val) {
  var answer = \"\";
  switch( val ) {
    case 1: case 2: case 3:
      answer = \"Low\";
      break;
    case 4: case 5: case 6:
      answer = \"Mid\";
      break;
    case 7: case 8: case 9:
      answer = \"High\";
      break;
    default:
      answer = \"Massive or Tiny?\";
  } 
  return answer;  
  }

  theTest(9);

Cheers.



回答3:

Here\'s different approach avoiding the switch statement altogether:

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

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


回答4:

In Js for assign multiple cases in switch We have to define different case without break like given below:

   <script type=\"text/javascript\">
      function checkHere(varName){
        switch (varName)
           {
           case \"saeed\":
           case \"larry\":
           case \"afshin\":
                alert(\'Hey\');
                break;
          case \"ss\":
             alert(\'ss\');
             break;
         default:
             alert(\'Default case\');
             break;
       }
      }
     </script>

Please see example click on link



回答5:

If you\'re using ES6, you can do this:

if ([\'afshin\', \'saeed\', \'larry\'].includes(varName)) {
   alert(\'Hey\');
} else {
   alert(\'Default case\');
}

Or for earlier versions of JavaScript, you can do this:

if ([\'afshin\', \'saeed\', \'larry\'].indexOf(varName) !== -1) {
   alert(\'Hey\');
} else {
   alert(\'Default case\');
}

Note that this won\'t work in older IE browsers, but you could patch things up fairly easily. See the question determine if string is in list in javascript for more information.



回答6:

you can use the \'in\' operator...
relies on the object/hash invocation...
so its as fast as javascript can be...

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

Enjoy, ZEE



回答7:

Adding and clarifying Stefano\'s answer, you can use expressions to dinamically set the values for the conditions in switch, e.g.:

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

So in your problem, you could do something like:

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

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

although not being so much DRY..



回答8:

In node it appears that you are allowed to do this:

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

This makes for much more compact code in some cases.



回答9:

It depends. Switch evaluates once and only once. Upon a match, all subsequent case statements until \'break\' fire no matter what the case says.

var onlyMen = true;
var onlyWomen = false;
var onlyAdults = false;
 
 (function(){
   switch (true){
     case onlyMen:
       console.log (\'onlymen\');
     case onlyWomen:
       console.log (\'onlyWomen\');
     case onlyAdults:
       console.log (\'onlyAdults\');
       break;
     default:
       console.log(\'default\');
   }
})(); // returns onlymen onlywomen onlyadults
<script src=\"https://getfirebug.com/firebug-lite-debug.js\"></script>



回答10:

switch (myVariable)
{
  case \"A\":
  case \"B\":
  case \"C\": 
    // Do something
    break;
  case \"D\":
  case \"E\":
    // Do something else
    break;
  default: 
    // Default case
    break;
}

In this example, if the value of myVariable is A, B, or C, it will execute the code under case \"C\":.



回答11:

I can see their are lots of good answers here, but what if happens when we need to check more than 10 cases? here is my approach.

 function isAccessible(varName){
     let accessDenied = [\'Liam\',\'Noah\',\'William\',\'James\',\'Logan\',\'Benjamin\',
                        \'Mason\',\'Elijah\',\'Oliver\',\'Jacob\',\'Daniel\',\'Lucas\'];
      switch (varName) {
         case (accessDenied.includes(varName)?varName:null): 
             return \'Access Denied!\';
         default:
           return \'Access Allowed.\';
       }
    }

    console.log(isAccessible(\'Liam\'));  


回答12:

I use like this:

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


回答13:

Another way of doing multiple cases in switch statement, when inside a function

 function name(varName){
      switch (varName) {
         case \'afshin\':
         case \'saeed\':
         case \'larry\':
           return \'Hey\';
         default:
           return \'Default case\';
       }
    }
            
    console.log(name(\'afshin\')); //Hey



回答14:

You could write it like this:

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

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


回答15:

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


回答16:

just switch the switch condition aprroach

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