Nested switch statement in javascript

前端 未结 4 1152
礼貌的吻别
礼貌的吻别 2021-02-05 05:34

Is it possible to use nested switch statement in javascript.

My code is some what look like

switch(id1)
{
case 1:
     switch(id2){
     ca         


        
相关标签:
4条回答
  • 2021-02-05 06:02

    You can use a nested switch statement but that can quickly become a spaghetti code and therefore it is not recommended. I would rather use functions with the nested switch statement for code clearance or maybe use recursive function depending on what the code is supposed to do.

    This is only a pseudo-code but I hope it gives you some idea on how to implement it. You have to be carefull to make the recursion stop on some given value of the ID. This pseudo-code increments the value of the ID by 1 if the value of the ID is 1, and increments by 2 if the value is 2. If the value is not 1 or 2 the recursion ends.

    function recursiveSwitch(var id) {
        switch(id) {
           case 1: 
               recursiveSwitch(id + 1);
               break;
           case 2
              recursiveSwitch(id + 2)
              break;
           default:
              return;
         }
    }
    
    0 讨论(0)
  • 2021-02-05 06:04

    Basically, it's possible but I think it depends on the complexity of the nesting if it's recommended to use nested switch statement or to use functions with the nested switch statement as Ómar Óskarsson has suggested.

    0 讨论(0)
  • 2021-02-05 06:13

    Your approach is absolutely fine.

    You can make the switch nesting less complex by using switch (true):

    switch (true) {
    case ((id1 === 1) && (id2 === 1) && (id3 === 1)) :
    case ((id1 === 1) && (id2 === 1) && (id3 === 2)) :
    case ((id1 === 1) && (id2 === 2) && (id3 === 1)) :
    case ((id1 === 1) && (id2 === 2) && (id3 === 2)) :
    case ((id1 === 2) && (id2 === 1) && (id3 === 1)) :
    case ((id1 === 2) && (id2 === 1) && (id3 === 2)) :
    case ((id1 === 2) && (id2 === 2) && (id3 === 1)) :
    case ((id1 === 2) && (id2 === 2) && (id3 === 2)) :
    }
    
    0 讨论(0)
  • 2021-02-05 06:18

    Yes, you can use inner switch like this way,

    Please check this demo : https://jsfiddle.net/1qsfropn/3/

    var text;
    var date = new Date()
    switch (date.getDay()) {
     case 1:
     case 2:
     case 3:
     default:
        text = "Looking forward to the Weekend";
        break;
     case 4:
     case 5:
        text = "Soon it is Weekend";
        break;
     case 0:
     case 6:
          switch(date.getFullYear()){
          case 2015:
            text = "It is Weekend of last Year.";
          break;
          case 2016:
            text = "It is Weekend of this Year.";
          break;
          case 2017:
            text = "It is Weekend of next Year.";
          break;
          default:
          text = date.getDay();
          break;
        }
    break;
    }
    document.getElementById("demo").innerHTML = text;`
    
    0 讨论(0)
提交回复
热议问题