我可以使用带有两个变量的 case/switch 语句吗?

发布于 2025-01-04 07:13:51 字数 268 浏览 1 评论 0原文

我是 JavaScript 的新手,据我了解,使用一个 SWITCH/CASE 语句比一大堆 IF 语句更快。

但是,我想使用带有两个变量的 SWITCH/CASE 语句。

我的网络应用程序有两个滑块,每个滑块都有五个状态。我希望行为基于这两个变量的状态。显然,这是一大堆 IF/THEN 语句。

我想到的一种方法是将两个变量连接成一个,然后我可以对其进行切换/区分。

有没有更好的方法使用两个变量来完成 SWITCH/CASE ?

谢谢 !

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.

However, I want to use a SWITCH/CASE statement with two variables.

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.

One way I thought about doing it was concatenating the two variables into one and then I could SWITCH/CASE that.

Is there a better way of accomplishing a SWITCH/CASE using two variables ?

Thanks !

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

梦太阳 2025-01-11 07:13:51

是的,你也可以这样做:

    switch (true) {

     case (var1 === true && var2 === true) :
       //do something
       break;
     case (var1 === false && var2 === false) :
       //do something
       break;

      default:

    }

这将始终执行开关,几乎就像 if/else 但看起来更干净。只需继续检查 case 表达式中的变量即可。

Yes you can also do:

    switch (true) {

     case (var1 === true && var2 === true) :
       //do something
       break;
     case (var1 === false && var2 === false) :
       //do something
       break;

      default:

    }

This will always execute the switch, pretty much just like if/else but looks cleaner. Just continue checking your variables in the case expressions.

青丝拂面 2025-01-11 07:13:51

按位运算符怎么样?您处理的是“枚举”,而不是字符串,它看起来更“优雅”。

// 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;


}

然而,我同意其他人的观点,switch-case 逻辑中的 25 个案例不太漂亮,而 if-else 在某些情况下可能“看起来”更好。反正。

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;


}

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.

酒与心事 2025-01-11 07:13:51
var var1 = "something";
var var2 = "something_else";
switch(var1 + "|" + var2) {
    case "something|something_else":
        ...
        break;
    case "something|...":
        break;
    case "...|...":
        break;
}

如果每一种都有 5 种可能性,那么您将得到 25 种情况。

var var1 = "something";
var var2 = "something_else";
switch(var1 + "|" + var2) {
    case "something|something_else":
        ...
        break;
    case "something|...":
        break;
    case "...|...":
        break;
}

If you have 5 possibilities for each one you will get 25 cases.

烟火散人牵绊 2025-01-11 07:13:51

首先,JavaScript 的 switch 并不比 if/else(有时慢得多)

其次,将 switch 与多个变量一起使用的唯一方法是将它们组合成一个原始(字符串、数字等)值:

var stateA = "foo";
var stateB = "bar";
switch (stateA + "-" + stateB) {
    case "foo-bar": ...
    ...
}

但是,就我个人而言,我宁愿看到一组 if< /code>/else 语句。

编辑:当所有值都是整数时,在 Chrome 中 switch 的性能似乎优于 if/else。看看评论。

First, JavaScript's switch is no faster than if/else (and sometimes much slower).

Second, the only way to use switch with multiple variables is to combine them into one primitive (string, number, etc) value:

var stateA = "foo";
var stateB = "bar";
switch (stateA + "-" + stateB) {
    case "foo-bar": ...
    ...
}

But, personally, I would rather see a set of if/else statements.

Edit: When all the values are integers, it appears that switch can out-perform if/else in Chrome. See the comments.

等往事风中吹 2025-01-11 07:13:51

我不相信 switch/case 比一系列 if/elseif 更快。它们做同样的事情,但是 if/elseif 可以检查多个变量。您不能对多个值使用 switch/case。

I don't believe a switch/case is any faster than a series of if/elseif's. They do the same thing, but if/elseif's you can check multiple variables. You cannot use a switch/case on more than one value.

做个少女永远怀春 2025-01-11 07:13:51

如果每个组合的动作是静态的,您可以构建一个二维数组:

var data = [
  [1,2,3,4,5],
  [6,7,8,9,10],
  [11,12,13,14,15],
  [16,17,18,19,20],
  [21,22,23,24,25]
];

上例中的数字可以是任何东西,例如字符串、数组等。现在获取值是单行的(假设滑块有一个值) [0,5) 的范围:

var info = data[firstSliderValue][secondSliderValue];

If the action of each combination is static, you could build a two-dimensional array:

var data = [
  [1,2,3,4,5],
  [6,7,8,9,10],
  [11,12,13,14,15],
  [16,17,18,19,20],
  [21,22,23,24,25]
];

The numbers in above example can be anything, such as string, array, etc. Fetching the value is now a one-liner (assuming sliders have a value range of [0,5):

var info = data[firstSliderValue][secondSliderValue];
月亮邮递员 2025-01-11 07:13:51

您可以为每个滑块上的每个位置指定一个从 1 到 1000000000 的不同二进制值
然后处理总和。

You could give each position on each slider a different binary value from 1 to 1000000000
and then work with the sum.

日裸衫吸 2025-01-11 07:13:51

是的,但不是以正常的方式。您将不得不使用 switch 作为关闭。

前任:-

function test(input1, input2) {
     switch (true) {
        case input1 > input2:
                    console.log(input1 + " is larger than " + input2);
                    break;
        case input1 < input2:
                    console.log(input2 + " is larger than " + input1);
        default:
                    console.log(input1 + " is equal to " + input2);
      }
   }

Yeah, But not in a normal way. You will have to use switch as closure.

ex:-

function test(input1, input2) {
     switch (true) {
        case input1 > input2:
                    console.log(input1 + " is larger than " + input2);
                    break;
        case input1 < input2:
                    console.log(input2 + " is larger than " + input1);
        default:
                    console.log(input1 + " is equal to " + input2);
      }
   }
妄断弥空 2025-01-11 07:13:51

我是这样做的:

switch (valueA && valueB) {

case true && false:
console.log(‘valueA is true, valueB is false’)
break;

case ( true || false ) && true:
console.log(‘valueA is either true or false and valueB is true’)
break;

default:
void 0;
}

I did it like this:

switch (valueA && valueB) {

case true && false:
console.log(‘valueA is true, valueB is false’)
break;

case ( true || false ) && true:
console.log(‘valueA is either true or false and valueB is true’)
break;

default:
void 0;
}
山色无中 2025-01-11 07:13:51

与上述串联方法相同,但更有品味 - 并且可能更有效? - 对于数字,您可以使用简单的双射(具体来说,我将其与几个正整数一起使用,并且我对浮点/实数双射没有任何信心

如果您只处理数字,则可以使用简单的双射

例如:Cantor 配对函数 从 N² 到 N

function c(a, b) {
  if (b === 0){
    return a * (a + 1) / 2;
  } else {
    return b + c(a + b, 0);
}

那么

function(a, b) {
  switch(c(a, b)) {
    case c(0, 0):
    // ...
    case c(1, 0):
    // ...
    case c(0, 1):
    // ...
    case c(1, 1):
    // ...
    case c(2, 1):
    // ...
  }
}

对于任何整数的元组来说,同样应该是安全可行的长度 n,因为 Z^n 与 N 具有相同的基数。

In the same vein as above-mentioned concatenation methods but more tastefully - and likely efficiently ? - for numbers you could use a simple bijection (specifically I used this with couples of positive integers, and I wouldn't have any confidence about floating point / real numbers bijections)

If you are only dealing with numbers, you could use simple bijections

For example : Cantor pairing function from N² to N

function c(a, b) {
  if (b === 0){
    return a * (a + 1) / 2;
  } else {
    return b + c(a + b, 0);
}

Then

function(a, b) {
  switch(c(a, b)) {
    case c(0, 0):
    // ...
    case c(1, 0):
    // ...
    case c(0, 1):
    // ...
    case c(1, 1):
    // ...
    case c(2, 1):
    // ...
  }
}

The same should be safely feasible for tuples of integers of any length n since Z^n has the same cardinality as N.

倦话 2025-01-11 07:13:51

这是我将采取的方法,我认为它比其他建议更清晰:

const doState = {
1: {
   1: func_1_1,
   2: func_1_2,
   3: function() { return false; }
   4: x => x-1,
   5: ...
   },
2: { ... }
...
}

const logic = doState[slider1] && doState[slider1][slider2]
if(!logic) return console.error("Unsupported program state")
return logic()

这可以让您将所有程序逻辑良好地组织成可以重用的离散函数,而不是处理条件,做正确的事情就是简单的字典查找。带有 && 的语句只是检查以确保第一项已定义,以避免未定义错误,返回值是逻辑结果,但您可以直接返回函数,具体取决于什么对你的申请有意义。

Here's the approach I would take, which I think is cleaner than the other proposals:

const doState = {
1: {
   1: func_1_1,
   2: func_1_2,
   3: function() { return false; }
   4: x => x-1,
   5: ...
   },
2: { ... }
...
}

const logic = doState[slider1] && doState[slider1][slider2]
if(!logic) return console.error("Unsupported program state")
return logic()

This lets you keep all your program logic well organized into discrete functions that can be reused and instead of dealing with conditionals doing the right thing is a simple dictionary lookup. The statement with the && is just checking to ensure the first item is defined to avoid an error on undefined, and the return value is the result of the logic but you could return the function directly depending on what makes sense in your application.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文