本文介绍了颠倒两个“或”的逻辑。 JavaScript中的语句,如果查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如果在JavaScript中进行
测试,它可以实现我想要的但不尽可能优雅。它是这样的:
I have an if
test in JavaScript which achieves what I want but not as elegantly as possible. It goes like this:
if (x > y || p < q) {
// don't do anything
} else {
doSomeFunction();
}
如果有任何方法可以翻转这个逻辑,那么只有一个 if
语句而不必具有虚拟if条件以及 else
条件?
If there any way to flip the logic of this so there's only a single if
statement without having to have a dummy if-condition as well as the else
condition?
推荐答案
您可以使用以反转条件:
You can use the !
operator to invert the condition:
if (!(x > y || p < q)) {
doSomeFunction();
}
或者只是改写这样的条件:
Or simply rewrite the condition like this:
if (x <= y && p >= q) {
doSomeFunction();
}
注意:参见,解释为什么这两个条件是相同的。
Note: See De Morgan's laws for an explanation about why these two conditions are equivalent.
这篇关于颠倒两个“或”的逻辑。 JavaScript中的语句,如果查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!