admin管理员组文章数量:1134246
I understand that in JavaScript you can write:
if (A && B) { do something }
But how do I implement an OR such as:
if (A OR B) { do something }
I understand that in JavaScript you can write:
if (A && B) { do something }
But how do I implement an OR such as:
if (A OR B) { do something }
Share
Improve this question
edited Jan 11, 2023 at 20:19
TylerH
21.2k76 gold badges79 silver badges110 bronze badges
asked Mar 2, 2010 at 14:38
sadmicrowavesadmicrowave
40.9k34 gold badges113 silver badges184 bronze badges
0
8 Answers
Reset to default 333Use the logical "OR" operator, that is ||
.
if (A || B)
Note that if you use string comparisons in the conditions, you need to perform a comparison for each condition:
if ( var1 == "A" || var1 == "B" )
If you only do it in the first one, then it will always return true:
if ( var1 == "A" || "B" ) //don't do this; it is equivalent to if ("B"), which is always true
The official ECMAScript documentation can be found here
Worth noting that ||
will also return true
if BOTH A
and B
are true
.
In JavaScript, if you're looking for A
or B
, but not both, you'll need to do something similar to:
if( (A && !B) || (B && !A) ) { ... }
if (A || B) { do something }
Use the ||
operator.
||
is the or operator.
if(A || B){ do something }
here is my example:
if(userAnswer==="Yes"||"yes"||"YeS"){
console.log("Too Bad!");
}
This says that if the answer is Yes yes or YeS than the same thing will happen
One can use regular expressions, too:
var thingToTest = "B";
if (/A|B/.test(thingToTest)) alert("Do something!")
Here's an example of regular expressions in general:
var myString = "This is my search subject"
if (/my/.test(myString)) alert("Do something here!")
This will look for "my" within the variable "myString". You can substitute a string directly in place of the "myString" variable.
As an added bonus you can add the case insensitive "i" and the global "g" to the search as well.
var myString = "This is my search subject"
if (/my/ig.test(myString)) alert("Do something here");
You may also want to filter an IF statement when condition1 equals 'something' AND condition2 equals 'another thing' OR 'something else'. You can do this by placing condition2 in another set of brackets eg...
if (condition1 === 'x' && (condition2 === 'y' || condition2 === 'z')) {
console.log('do whatever')
}
If condition2 is NOT in it's own brackets then condition1 has to be x AND condition2 has to be y for the function to trigger...
... but it will also trigger if condition2 is z, regardless of what condition1 is. Which may be okay depending on your use case, but something to be mindful of.
本文标签: How to use OR condition in a JavaScript IF statementStack Overflow
版权声明:本文标题:How to use OR condition in a JavaScript IF statement? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736748816a1950924.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论