Reverse the logic of two “or” statements in JavaScript if query

我们两清 提交于 2019-12-13 01:44:40

问题


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 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?


回答1:


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.




回答2:


You can simply invert the comparisons and the logical OR.

if (x <= y && p >= q) {
    doSomeFunction();
}



回答3:


Along with the other answer, the last option (less readable) is :

(x > y || p < q) || doSomeFunction();

If the left bracket is true, it will NOT execute the function.



来源:https://stackoverflow.com/questions/22967064/reverse-the-logic-of-two-or-statements-in-javascript-if-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!