javascript中嵌套的switch语句

sha*_*ngh 16 javascript switch-statement

是否可以switch在javascript中使用嵌套语句.

我的代码是一些看起来像

switch(id1)
{
case 1:
     switch(id2){
     case 1:{
        switch(id3){
        case 1:{}
        case 2:{}
        }
    }
     case 2:{
        switch(id4){
        case 1:{}
        case 2:{}
        }
     }
}
case 2:
}
Run Code Online (Sandbox Code Playgroud)

如果是,那么这是一个很好的做法,或者我们可以使用任何替代方法.

Rou*_*ica 29

你的方法绝对没问题.

您可以switch使用以下方法使嵌套不那么复杂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)) :
}
Run Code Online (Sandbox Code Playgroud)

  • 习惯的力量,尼娜。:-) (3认同)
  • 你可以省略case子句中的括号. (2认同)

Joe*_*ity 10

是的,你可以像这样使用内部开关,

请查看此演示: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;`
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用嵌套的 switch 语句,但它很快就会变成意大利面条式代码,因此不推荐使用。我宁愿使用带有嵌套 switch 语句的函数来清除代码,或者可能使用递归函数,具体取决于代码应该做什么。

这只是一个伪代码,但我希望它能让您对如何实现它有所了解。您必须小心地使递归停止在某个给定的 ID 值上。如果 ID 的值为 1,则此伪代码将 ID 的值加 1,如果值为 2,则将 ID 的值加 2。如果值不是 1 或 2,则递归结束。

function recursiveSwitch(var id) {
    switch(id) {
       case 1: 
           recursiveSwitch(id + 1);
           break;
       case 2
          recursiveSwitch(id + 2)
          break;
       default:
          return;
     }
}
Run Code Online (Sandbox Code Playgroud)