我可以以某种方式在switch中使用if语句添加更多案例吗?

Geo*_*rov 6 javascript variables if-statement switch-statement

我正在尝试编写一个"switch"语句,但我已经严格定义了case,我想尽可能少地使用代码.因此,当我想知道怎么做时,我想到了一个想法,是否有可能在"switch"中添加"if"语句,所以如果这个"if"语句为真,可以在我的"switch"中添加更多的情况.例如:

switch(myVar) {
    case 1: 
        return 'Your variable is 1';
    case 2: 
        return 'Your variable is 2';
    if(yourVar && yourVar === true) {
        case 3: return 'Your variable is 3';
    }
    default: return 0;
}
Run Code Online (Sandbox Code Playgroud)

PS我使用的真实场景更复杂,代码非常长,所以如果它们适合用例,那么欢迎任何sugestions.

LGS*_*Son 2

你可以这样做

function test(myVar, yourVar) {

  switch(myVar) {
    case 1: return '1';
    case 2: return '2';

    default:
      // as requested in a comment, add yourVar to myVar
      if(myVar != undefined && yourVar != undefined) return myVar + yourVar;

      return '0';
  }
}

alert(test(2));
alert(test(3));
alert(test(3,5));
alert(test(3,0));
Run Code Online (Sandbox Code Playgroud)