using OR operator in javascript switch statement [duplicate]
I'm doing a switch statement in javascript:
switch($tp_type){
case 'ITP':
$('#indv_tp_id').val(data);
break;
case 'CRP'||'COO'||'FOU':
$('#jurd_tp_i开发者_运维问答d').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!
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:
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.
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.
精彩评论