如何在 Javascript 中编写 OR?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12266142/
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
How to write OR in Javascript?
提问by Dany
How do you write OR
in Javascript?
你是如何OR
用 Javascript编写的?
Example :
例子 :
if ( age **or** name == null ){
do something
}
回答by David says reinstate Monica
Simply use:
只需使用:
if ( age == null || name == null ){
// do something
}
Although, if you're simply testing to see if the variables have a value (and so are 'falsey' rather than equal to null
) you could use instead:
虽然,如果您只是简单地测试变量是否具有值(因此是 'falsey' 而不是 equal to null
),您可以改用:
if ( !age || !name ){
// do something
}
References:
参考:
回答by user1103976
if (age == null || name == null) {
}
Note: You may want to see this thread, Why is null an object and what's the difference between null and undefined?, for information on null/undefined variables in JS.
注意:你可能想看看这个线程,为什么 null 是一个对象,null 和 undefined 之间有什么区别?, 有关 JS 中空/未定义变量的信息。
回答by Stephen Garle
The problem you are having is the way that or associates. (age or name == null)
will actually be ((age or name) == null)
, which is not what you want to say. You want ((age == null) or (name == null))
. When in doubt, insert parentheses. If you put in parentheses and evaluated, you would have seen that the situations became something like (true == null)
and (false == null)
.
您遇到的问题是方式或关联。 (age or name == null)
实际上将是((age or name) == null)
,这不是您想说的。你要((age == null) or (name == null))
。如有疑问,请插入括号。如果您放入括号并进行评估,您会看到情况变成了(true == null)
和(false == null)
。
回答by Alireza
We don't have ORoperator in JavaScript,we use ||
instead, in your case do...:
我们在JavaScript 中没有OR运算符,我们||
改为使用,在您的情况下做...:
if (age || name == null) {
//do something
}