我可以使用带有两个变量的 case/switch 语句吗?
我是 JavaScript 的新手,我的理解是使用一个 SWITCH/CASE 语句比使用一大堆 IF 语句要快.
I am a newbie when it comes to JavaScript and it was my understanding that using one SWITCH/CASE statements is faster than a whole bunch of IF statements.
但是,我想使用带有两个变量的 SWITCH/CASE 语句.
However, I want to use a SWITCH/CASE statement with two variables.
我的网络应用有两个滑块,每个滑块有五个状态.我希望行为基于这两个变量的状态.显然,这是一大堆 IF/THEN 语句.
My web app has two sliders, each of which have five states. I want the behavior to be based on the states of these two variables. Obviously that is a whole heck of a lot of IF/THEN statements.
我想到的一种方法是将两个变量连接成一个变量,然后我可以 SWITCH/CASE 那个.
One way I thought about doing it was concatenating the two variables into one and then I could SWITCH/CASE that.
有没有更好的方法来完成使用两个变量的 SWITCH/CASE ?
Is there a better way of accomplishing a SWITCH/CASE using two variables ?
谢谢!
推荐答案
是的,你也可以这样做:
Yes you can also do:
switch (true) {
case (var1 === true && var2 === true) :
//do something
break;
case (var1 === false && var2 === false) :
//do something
break;
default:
}
这将始终执行切换,与 if/else 非常相似,但看起来更简洁.只需继续检查 case 表达式中的变量即可.
This will always execute the switch, pretty much just like if/else but looks cleaner. Just continue checking your variables in the case expressions.
相关文章