switch case 语句中的表达式

2022-01-19 00:00:00 switch-statement javascript case

我正在尝试创建一个 switch 语句,但我似乎无法使用被评估的表达式(而不是设置的字符串/整数).我可以使用 if 语句轻松地做到这一点,但希望 case 更快.

I'm trying to create a switch statement but I can't seem to be able to use an expression that gets evaluated (rather than a set string/integer). I can easily do this with if statements but case should hopefully be faster.

我正在尝试以下方法

function reward(amount) {
    var $reward = $("#reward");
    switch (amount) {
        case (amount >= 7500 && amount < 10000):
            $reward.text("Play Station 3");
            break;
        case (amount >= 10000 && amount < 15000):
            $reward.text("XBOX 360");
            break;
        case (amount >= 15000):
            $reward.text("iMac");
            break;
        default:
            $reward.text("No reward");
            break;
    }
}

我是否遗漏了一些明显的东西,或者这不可能?Google 在这种情况下并不友好.

Am i missing something obvious or is this not possible? Google hasn't been friendly in this case.

任何帮助/指针表示赞赏

M

推荐答案

你总是可以做到的

switch (true) {
  case (amount >= 7500 && amount < 10000):
    //code
    break;
  case (amount >= 10000 && amount < 15000):
    //code
    break;

  //etc...

之所以有效,是因为 true 是一个常量,所以第一个 case 语句下的表达式为 true 的代码将被执行.

It works because true is a constant, so the code under the first case statement with an expression that evaluates to true will be executed.

我想这有点棘手",但我认为使用它没有任何问题.一个简单的 if/else 语句可能会更简洁,您不必担心意外掉线.但无论如何,它就在那里.

It's kinda "tricky" I guess, but I see nothing wrong with using it. A simple if/else statement would probably be more concise, and you'd not have to worry about accidental fall-through. But there it is anyway.

相关文章