问题
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