我想知道是否可以将多个 if
语句重写为 switch
。
问题是switch
运行:
案例通过检查后的所有代码。这就是为什么 case 语句在第一个 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'); }
- 如果某个开关在每种情况下都有中断,则它会运行一个通过测试的案例。
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;
}
所以问题是:如何将多个 if
语句重写为单个 switch
语句?
如果我不能:是否有比多个 if
语句更优雅的语法,这使得我明显在进行类似的比较?
最佳答案
How can I rewrite multiple if statements into a single switch statement?
如果您希望多个案例匹配,那么您就不能合理地进行匹配。 switch
可以替换 if
/else
,但不能替换一系列独立的 if
,其中多个可以匹配。
Is there another more elegant syntax than the multiple if statements, that makes it apparent that I am making similar comparisons?
这里的答案往往特定于您正在编写的代码。有几个选项供您选择:
参数化为函数
每当您的代码反复执行相同的操作时,请将其参数化并将其放入函数中,然后使用参数重复调用该函数。
function doTheThing(value) {
if (arr.includes(value)) {
console.log('xyz ' + value);
}
}
例如,在您的示例中:
function doTheThing(value) {
if (arr.includes(value)) {
console.log('xyz ' + value);
}
}
let arr = [1, 3];
doTheThing(1);
doTheThing(2);
doTheThing(3);
或
let arr = [1, 3];
[1, 2, 3].forEach(value => {
if (arr.includes(value)) {
console.log("xyz " + value);
}
});
或组合这些:
function doTheThing(value) {
if (arr.includes(value)) {
console.log('xyz ' + value);
}
}
let arr = [1, 3];
[1, 2, 3].forEach(doTheThing);
将操作作为函数的查找表
如果您正在做不同的事情,一种常见的做法是建立一个值(value)到行动的查找表,例如:
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);
});
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");
}
};
<小时/>
旁注:您永远不需要 === true
和 Array#includes
。它总是返回一个 bool 值。
关于javascript - 如何使用 switch 而不是多个 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49978305/