Expression inside switch case statement(switch 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.
这篇关于switch case 语句中的表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:switch case 语句中的表达式
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Fetch API 如何获取响应体? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01