颠倒两个“或"的逻辑.JavaScript中的语句(如果查询) [英] Reverse the logic of two "or" statements in JavaScript if query

查看:45
本文介绍了颠倒两个“或"的逻辑.JavaScript中的语句(如果查询)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中进行了 if 测试,该测试可以实现我想要的功能,但效果却不太好.它是这样的:

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中的语句(如果查询)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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