如何在 JavaScript IF 语句中使用 OR 条件?
我知道在 JavaScript 中你可以这样写:
if (A && B) { do something }
但是我如何实现一个 OR,例如:
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 }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
使用逻辑“OR”运算符 ,即
||
。请注意,如果在条件中使用字符串比较,则需要对每个条件进行比较:
如果只在第一个条件中进行比较,那么它将始终返回 true:
官方 ECMAScript 文档可以可以在此处找到
Use the logical "OR" operator, that is
||
.Note that if you use string comparisons in the conditions, you need to perform a comparison for each condition:
If you only do it in the first one, then it will always return true:
The official ECMAScript documentation can be found here
值得注意的是,如果
A
和B
均为true
,||
也会返回true
>。在 JavaScript 中,如果您要查找
A
或B
,但不是两者都,则需要执行类似于以下操作的操作:Worth noting that
||
will also returntrue
if BOTHA
andB
aretrue
.In JavaScript, if you're looking for
A
orB
, but not both, you'll need to do something similar to:使用
||
运算符。Use the
||
operator.||
是或运算符。||
is the or operator.这是我的例子:
这表示如果答案是“是”或“是”,则会发生同样的事情
here is my example:
This says that if the answer is Yes yes or YeS than the same thing will happen
也可以使用正则表达式:
下面是一般正则表达式的示例:
这将在变量“myString”中查找“my”。您可以直接用字符串代替“myString”变量。
作为额外的好处,您还可以将不区分大小写的“i”和全局“g”添加到搜索中。
One can use regular expressions, too:
Here's an example of regular expressions in general:
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.
您可能还想在条件 1 等于“某事”且条件 2 等于“另一件事”或“其他事物”时过滤 IF 语句。您可以通过将条件2放在另一组括号中来完成此操作,例如...
如果条件2在它自己的括号中NOT,则条件1 必须是 x 并且条件2 必须是 y 才能触发该函数...
...但如果条件2 是 z,它也会触发,无论如何条件1是什么。根据您的用例,这可能没问题,但需要注意一些事情。
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 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.