如何使用switch而不是多个if语句?

RMo*_*RMo 0 javascript if-statement switch-statement

我想知道是否有可能将多个if语句重写为switch.

问题是switch运行:

  1. 案件通过检查后的所有代码.这就是为什么case语句在第一个案例之后运行所有代码的原因.

    let arr = [1, 3];
    
    if( arr.includes(1) === true ) {
      console.log('if 1');
    }
    if( arr.includes(2) === true) {
      console.log('if 2');
    }
    if( arr.includes(3) === true) {
      console.log('if 3');
    }
    
    
    switch( true ){
      case arr.includes(1):
        console.log('switch 1');
      case arr.includes(2): 
        console.log('switch 2');
      case arr.includes(3): 
        console.log('switch 3');
    }
    Run Code Online (Sandbox Code Playgroud)

    1. 如果一个开关在每种情况下都有中断,它会运行一个案例,通过测试.

let arr = [1, 3];

if( arr.includes(1) === true ) {
  console.log('if 1');
}
if( arr.includes(2) === true) {
  console.log('if 2');
}
if( arr.includes(3) === true) {
  console.log('if 3');
}


switch( true ){
  case arr.includes(1):
    console.log('switch 1');
    break;
  case arr.includes(2): 
    console.log('switch 2');
    break;
  case arr.includes(3): 
    console.log('switch 3');
    break;
}
Run Code Online (Sandbox Code Playgroud)

所以问题是:如何将多个if语句重写为单个switch语句?

如果我不能:是否有比多if语句更优雅的语法,这显然表明我正在进行类似的比较?

T.J*_*der 5

如何将多个if语句重写为单个switch语句?

合理地说,如果您想要多个案例匹配,则不能.switch可以替换if/ else,但不能替换一系列独立的ifs,其中多个可以匹配.

是否有比if多语句更优雅的语法,这显然表明我正在进行类似的比较?

这里的答案将倾向于特定于您正在编写的代码.有几种选择:

参数化为一个函数

每当你有代码你反复做同样的事情时,参数化它并把它放在一个函数中,然后用参数重复调用函数.

function doTheThing(value) {
  if (arr.includes(value)) {
    console.log('xyz ' + value);
  }
}
Run Code Online (Sandbox Code Playgroud)

例如,在您的示例中:

function doTheThing(value) {
  if (arr.includes(value)) {
    console.log('xyz ' + value);
  }
}

let arr = [1, 3];
doTheThing(1);
doTheThing(2);
doTheThing(3);
Run Code Online (Sandbox Code Playgroud)

要么

let arr = [1, 3];
[1, 2, 3].forEach(value => {
    if (arr.includes(value)) {
        console.log("xyz " + value);
    }
});
Run Code Online (Sandbox Code Playgroud)

或者结合那些:

function doTheThing(value) {
  if (arr.includes(value)) {
    console.log('xyz ' + value);
  }
}

let arr = [1, 3];
[1, 2, 3].forEach(doTheThing);
Run Code Online (Sandbox Code Playgroud)

将操作作为函数的查找表

如果你正在做不同的事情,一个常见的做法是有一个价值与行动的查找表,例如:

const actionsByValue = {
  1() {
    console.log("This is the thing for #1");
  },
  2() {
    console.log("This is something else for #2");
  },
  3() {
    console.log("Different logic again for #3");
  }
};
const nop = () => { };

let arr = [1, 3];
arr.forEach(value => {
  (actionsByValue[value] || nop)(value);
});
Run Code Online (Sandbox Code Playgroud)

这种1() { }表示法可能看起来很奇怪,因为你没有经常看到带有数字名称的属性的方法表示法,但它完全有效.在不支持方法表示法的旧环境中:

const actionsByValue = {
  1: function() {
    console.log("This is the thing for #1");
  },
  2: function() {
    console.log("This is something else for #2");
  },
  3: function() {
    console.log("Different logic again for #3");
  }
};
Run Code Online (Sandbox Code Playgroud)

附注:任何时候都不需要=== true用Array#includes.它总是返回一个布尔值.