JavaScript, Typescript switch statement: way to run same code for two cases?

前端 未结 5 641
心在旅途
心在旅途 2020-12-29 02:22

Is there a way to assign two different case values to the same block of code without copy and pasting? For example, below 68 and 40 should execute the same code, while 30 is

相关标签:
5条回答
  • 2020-12-29 02:24
    case 68:
    case 40:
      // stuff
      break;
    
    0 讨论(0)
  • 2020-12-29 02:25

    Switch cases can be clubbed as shown in the dig.

    Also, It is not limited to just two cases, you can extend it to any no. of cases.

    0 讨论(0)
  • 2020-12-29 02:32

    You should use:

    switch condition {
      case 1,2,3:
        // do something
      case 4,5:
        // do something
      default:
        // do something
    }
    

    Cases should be comma-separated.

    0 讨论(0)
  • 2020-12-29 02:34

    Just put them right after each other without a break

    switch (myVar) {
      case 68:
      case 40:
        // Do stuff
      break;
    
      case 30:
        // Do stuff
      break;
    }
    
    0 讨论(0)
  • 2020-12-29 02:42

    Yes, you just put the related case statements next to each other, like this:

    case 40:  // Fallthrough
    case 68:
       // Do something
       break;
    
    case 30:
       // Do something different
       break;
    

    The Fallthrough comment is there for two reasons:

    • It reassures human readers that you're doing this deliberately
    • It silences warnings from Lint-like tools that issue warnings about possible accidental fallthrough.
    0 讨论(0)
提交回复
热议问题