Nested switch statement in javascript

前端 未结 4 1176
礼貌的吻别
礼貌的吻别 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;
         }
    }
    

提交回复
热议问题