表达式在switch case语句中 [英] Expression inside switch case statement

查看:201
本文介绍了表达式在switch case语句中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个switch语句,但我似乎无法使用得到评估的表达式(而不是设置字符串/整数)。我可以轻松地使用if语句执行此操作,但希望案例更快。

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

我错过了一些明显的东西,或者这是不可能的?谷歌在这种情况下并不友好。

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.

这篇关于表达式在switch case语句中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆