Test for multiple cases in a switch, like an OR (||)

后端 未结 6 647
暗喜
暗喜 2020-11-28 01:16

How would you use a switch case when you need to test for a or b in the same case?

switch (pagei         


        
6条回答
  •  忘掉有多难
    2020-11-28 01:42

    Since the other answers explained how to do it without actually explaining why it works:

    When the switch executes, it finds the first matching case statement and then executes each line of code after the switch until it hits either a break statement or the end of the switch (or a return statement to leave the entire containing function). When you deliberately omit the break so that code under the next case gets executed too that's called a fall-through. So for the OP's requirement:

    switch (pageid) {
       case "listing-page":
       case "home-page":
          alert("hello");
          break;
    
       case "details-page":
          alert("goodbye");
          break;
    } 
    

    Forgetting to include break statements is a fairly common coding mistake and is the first thing you should look for if your switch isn't working the way you expected. For that reason some people like to put a comment in to say "fall through" to make it clear when break statements have been omitted on purpose. I do that in the following example since it is a bit more complicated and shows how some cases can include code to execute before they fall-through:

    switch (someVar) {
       case 1:
          someFunction();
          alert("It was 1");
          // fall through
       case 2:
          alert("The 2 case");
          // fall through
       case 3:
          // fall through
       case 4:
          // fall through
       case 5:
          alert("The 5 case");
          // fall through
       case 6:
          alert("The 6 case");
          break;
    
       case 7:
          alert("Something else");
          break;
    
       case 8:
          // fall through
       default:
          alert("The end");
          break;
    }
    

    You can also (optionally) include a default case, which will be executed if none of the other cases match - if you don't include a default and no cases match then nothing happens. You can (optionally) fall through to the default case.

    So in my second example if someVar is 1 it would call someFunction() and then you would see four alerts as it falls through multiple cases some of which have alerts under them. Is someVar is 3, 4 or 5 you'd see two alerts. If someVar is 7 you'd see "Something else" and if it is 8 or any other value you'd see "The end".

提交回复
热议问题