在javascript switch语句中使用OR运算符 [英] using OR operator in javascript switch statement

查看:852
本文介绍了在javascript switch语句中使用OR运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用javascript做一个switch语句:

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_id').val(data);
    break;

}

但是我认为如果我使用OR运算符是行不通的.如何在javascript中正确执行此操作? 如果选择ITP,我将获得ITP.但是,如果我选择COO,FOU或CRP,则我总是得到第一个CRP.请帮忙,谢谢!

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!

推荐答案

您应该这样重写它:

case 'CRP':
case 'COO':
case 'FOU':
  $('#jurd_tp_id').val(data);
  break;

您可以在 switch 参考文献中看到该文档.此处描述了连续的case语句之间没有break的行为(称为穿透"):

You can see it documented in the switch reference. The behavior of consecutive case statements without breaks in between (called "fall-through") is described there:

与每个case标签关联的可选break语句可确保一旦执行匹配的语句,程序就退出switch并在switch之后的语句处继续执行. 如果省略break,程序将在switch语句中的下一个语句处继续执行.

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.

关于为什么您的版本仅适用于第一项(CRP)的原因,仅是因为表达式'CRP'||'COO'||'FOU'的计算结果为'CRP'(因为在布尔上下文中非空字符串的计算结果为true).因此,一旦计算case语句就等同于case 'CRP':.

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.

这篇关于在javascript switch语句中使用OR运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆