本文介绍了在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:

关于为什么您的版本仅适用于第一项(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运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 00:10
查看更多