简体   繁体   English

如何使用JavaScript在切换案例中调用案例?

[英]How to call case within switch case using javascript?

I have switch case like as below 我有如下的开关盒

  switch(something){
      case 1:
             break;
      case 2:
             break;
      case 3:
             break;
      default:
             break;
    }

Now i want to call case 1 within case 3 is it possible? 现在我想在情况3中调用情况1吗?

Just wrap the operations in functions so they are reusable 只需将操作包装在函数中即可重用

switch (something) {
case 1:
    operation1();
    break;
case 2:
    operation2();
    break;
case 3:
    operation3()
    operation1(); //call operation 1
    break;
default:
    defaultOperation();
    break;
}

You could do it like so: 您可以这样做:

switch(something){
  case 2:
         break;
  case 3:
         //do something and fall through
  case 1:
         //do something else
         break;
  default:
         break;
}

normally all code below a matched case will be executed. 通常情况下,匹配情况下的所有代码都将执行。 So if you omit the break; 因此,如果您忽略break; statement, you will automatically fall through to the next case and execute the code inside. 语句,您将自动进入下一种情况并执行其中的代码。

  switch(something){
      case 3:
      case 1:
             break;
      case 2:
             break;

      default:
             break;
    }

this should do the trick 这应该可以解决问题

combine the two cases: 结合两种情况:

switch(something){
   case 1:
   case 3:
          break;
   case 2:
          break;
   default:
          break;
 } 
var i = 3;

switch (i)
{
    case(3):
    alert("This is the case for three");

    case(1):
    alert("The case has dropped through");
    break;
    case(2):
    alert("This hasn't though");
    break;
}  

Not really a good idea though, leads to unreadable code 但是,这并不是一个好主意,导致代码无法读取

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM