在jQuery if语句中使用OR运算符 [英] Using OR operator in a jquery if statement

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

问题描述

我需要在jQuery if语句中使用OR运算符以过滤出10个状态.我的代码仅在排除一个状态时有效,但是在尝试包含多个状态时失败.有正确的方法吗?

我正在使用的代码:

if ((state != 10) || (state != 15) || (state != 19) || 
    (state != 22) || (state != 33) || (state != 39) || 
    (state != 47) || (state != 48) || (state != 49) || 
    (state != 51)) 
   return true;

谢谢

解决方案

考虑什么

if ((state != 10) || (state != 15) || (state != 19) || (state != 22) || (state != 33) || (state != 39) || (state != 47) || (state != 48) || (state != 49) || (state != 51))

表示. ||表示或".的否定是(根据戴摩根定律):

state == 10 && state == 15 && state == 19...

换句话说,如果state同时等于10、15和19(以及您的or语句中的其余数字),那么唯一的可能是错误的,这是不可能的. /p>

因此,此语句将始终为true.例如,状态15永远不会等于状态10,因此始终总是state不等于10或不等于15.

||更改为&&.

在大多数语言中,以下内容也是如此:

if (x) {
  return true;
}
else {
  return false;
}

不是必需的.在这种情况下,方法完全在x为true时返回true,在xfalse时恰好返回false.您可以这样做:

return x;

I need to use the OR operator in a jQuery if statement to filter out 10 states. My code works wile only excluding one state, but fails when i try to include multiple states. Is there a correct way to do this?

Code I am am using :

if ((state != 10) || (state != 15) || (state != 19) || 
    (state != 22) || (state != 33) || (state != 39) || 
    (state != 47) || (state != 48) || (state != 49) || 
    (state != 51)) 
   return true;

Thanks

解决方案

Think about what

if ((state != 10) || (state != 15) || (state != 19) || (state != 22) || (state != 33) || (state != 39) || (state != 47) || (state != 48) || (state != 49) || (state != 51))

means. || means "or." The negation of this is (by DeMorgan's Laws):

state == 10 && state == 15 && state == 19...

In other words, the only way that this could be false if if a state equals 10, 15, and 19 (and the rest of the numbers in your or statement) at the same time, which is impossible.

Thus, this statement will always be true. State 15 will never equal state 10, for example, so it's always true that state will either not equal 10 or not equal 15.

Change || to &&.

Also, in most languages, the following:

if (x) {
  return true;
}
else {
  return false;
}

is not necessary. In this case, the method returns true exactly when x is true and false exactly when x is false. You can just do:

return x;

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

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