我可以使用带有两个变量的case / switch语句吗? [英] Can I use a case/switch statement with two variables?
问题描述
对于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 ?
谢谢!
推荐答案
按位运算符怎么样?而不是字符串,你正在处理enums,它看起来更优雅。
How about a bitwise operator? Instead of strings, you're dealing with "enums", which looks more "elegant."
// Declare slider's state "enum"
var SliderOne = {
A: 1,
B: 2,
C: 4,
D: 8,
E: 16
};
var SliderTwo = {
A: 32,
B: 64,
C: 128,
D: 256,
E: 512
};
// Set state
var s1 = SliderOne.A,
s2 = SliderTwo.B;
// Switch state
switch (s1 | s2) {
case SliderOne.A | SliderTwo.A :
case SliderOne.A | SliderTwo.C :
// Logic when State #1 is A, and State #2 is either A or C
break;
case SliderOne.B | SliderTwo.C :
// Logic when State #1 is B, and State #2 is C
break;
case SliderOne.E | SliderTwo.E :
default:
// Logic when State #1 is E, and State #2 is E or
// none of above match
break;
}
我同意其他人,25例在一个switch-case逻辑中并不是太漂亮,而且在某些情况下if-else可能会看起来更好。无论如何。
I however agree with others, 25 cases in a switch-case logic is not too pretty, and if-else might, in some cases, "look" better. Anyway.
这篇关于我可以使用带有两个变量的case / switch语句吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!