Javascript javascript开关(真)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2765981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript switch(true)
提问by ntan
Hi i am trying to handle an ajax json response
嗨,我正在尝试处理 ajax json 响应
here is my code
这是我的代码
success: function (j) {
switch(true)
{
case (j.choice1):
alert("choice2");
break;
case (j.choice2):
alert("choice2");
break;
default:
alert("default");
break;
}
}
based on what j is return i do my action BUT i keep getting the default.
基于什么 j 返回我做我的动作,但我一直得到默认值。
I have alert the j values and come correct.Some how case (j.choice1) case (j.choice2) is not working.
我已经提醒 j 值并正确。一些案例(j.choice1)案例(j.choice2)不起作用。
I tried case (j.choice1!="") (j.choice2!="") But in this scenario i keep getting the first choice.
我试过 case (j.choice1!="") (j.choice2!="") 但在这种情况下我一直得到第一选择。
What am i missing
我错过了什么
回答by SLaks
It works for me:
这个对我有用:
var a = 0, b = true;
switch(true) {
case a:
console.log('a');
break;
case b:
console.log('b');
break;
}
However, the caselabels must be equal to true, not jut implicitly true.
Also, only the first case that evaluates to truewill execute.
但是,case标签必须等于true,而不是隐含地为真。
此外,只有评估为的第一个案例true才会执行。
回答by ntan
SOLVED
解决了
Based on SLaks answer i modify the code as below
基于 SLaks 回答我修改代码如下
if(j.choice1){ var choice1=true;} else { var choice1=false;}
if(j.choice2){ var choice2=true;} else { var choice2=false;}
switch(true)
{
case choice1:
alert("choice1");
break;
case choice2:
alert("choice2");
break;
default:
alert("default");
break;
}
For all asking why switch and not if.
对于所有询问为什么切换而不是如果的问题。
Switch will execute only 1 statement, but if can execute more than 1 if any mistake come form response (for example if set choice1 and choice 2 the if will alert both but switch will alert only choice1).
Switch 将只执行 1 条语句,但如果在响应中出现任何错误,则可以执行 1 条以上的语句(例如,如果设置了 choice1 和 choice2,if 会同时提醒两者,但 switch 只会提醒 choice1)。
The response expecting as choice has to do with credit card charge to bank so i want to ensure that only 1 action will exetute
期望作为选择的响应与向银行收取信用卡费用有关,因此我想确保只有 1 个操作会执行
Thank to all
感谢大家
回答by Oded
You need to read up on the switchstatement. You should not be switching on a constant value.
你需要仔细阅读switch声明。你不应该打开一个常数值。
It appears that you need to use if statements, as you don't really want to be switching on your jvalue:
看来您需要使用 if 语句,因为您真的不想打开您的j值:
success: function (j) {
if (j.choice1)
{
alert("choice1");
break;
}
if (j.choice2)
{
alert("choice2");
break;
}
alert("default");
}
}
回答by Syntactic
In a case like this, a better way to do this is probably something like:
在这种情况下,更好的方法可能是:
success: function (j) {
if(j.choice1 || j.choice2) {
alert("choice2");
} else {
alert("default");
}
}

