在 javascript switch 语句中使用 OR 运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6476994/
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
using OR operator in javascript switch statement
提问by Wern Ancheta
I'm doing a switch statement in javascript:
我在 javascript 中做一个 switch 语句:
switch($tp_type){
case 'ITP':
$('#indv_tp_id').val(data);
break;
case 'CRP'||'COO'||'FOU':
$('#jurd_tp_id').val(data);
break;
}
But I think it doesn't work if I use OR operator. How do I properly do this in javascript? If I choose ITP,I get ITP. But if I choose either COO, FOU OR CRP I always get the first one which is CRP. Please help, thanks!
但我认为如果我使用 OR 运算符,它就不起作用。我如何在 javascript 中正确地做到这一点?如果我选择ITP,我就会得到ITP。但如果我选择 COO、FOU 或 CRP,我总是得到第一个 CRP。请帮忙,谢谢!
回答by Mat
You should re-write it like this:
你应该像这样重写它:
case 'CRP':
case 'COO':
case 'FOU':
$('#jurd_tp_id').val(data);
break;
You can see it documented in the switch
reference. The behavior of consecutive case
statements without break
s in between (called "fall-through") is described there:
您可以在switch
参考资料中看到它的记录。中间case
没有break
s的连续语句的行为(称为“fall-through”)在那里描述:
The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.
与每个 case 标签相关联的可选 break 语句确保程序在执行匹配的语句后中断 switch 并在 switch 之后的语句处继续执行。如果省略 break ,程序将在 switch 语句中的下一个语句处继续执行。
As for why your version only works for the first item (CRP
), it's simply because the expression 'CRP'||'COO'||'FOU'
evaluates to 'CRP'
(since non-empty strings evaluate to true
in Boolean context). So that case
statement is equivalent to just case 'CRP':
once evaluated.
至于为什么您的版本仅适用于第一项 ( CRP
),这仅仅是因为表达式的'CRP'||'COO'||'FOU'
计算结果为'CRP'
(因为true
在布尔上下文中非空字符串的计算结果为)。因此该case
语句等效于仅case 'CRP':
评估一次。