问题描述
我正在尝试创建一个 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 语句中的表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)