复杂的 IF 语句问题
Complex IF statement issue
if
语句中有一个复杂的条件,不知怎么的,它无法按照我的要求运行。
if (
(statementA1) ||
(statementA2) &&
(statementB) &&
(statementC)
) {
doSomething
}
A1
和 A2
不能同时为真(因为实际陈述的性质)。
此外,B
和 C
都必须评估 true 才能得出整体 true。
所以只有 true false true true
和 false true true true
应该 return true
;任何其他排列应该 return false
.
由于其内部复杂性(包括 Math.abs()
、A1
和 B
具有内部组合子语句),这些语句位于大括号中。
对于
a1 a2 b c result
----- ----- ----- ----- ------
true false true true true
false true true true true
true true true true true <- different from blow
你可以使用这个表达式
(a1 || a2) && b && c
a1
或 a2
和 b
和 c
。
if ((statementA1 || statementA2) && statementB && statementC) {
// doSomething
}
你需要括号因为 operator precedence of logical AND &&
(6) over logical OR ||
(5)
如果你有的话
a1 a2 b c result
----- ----- ----- ----- ------
true false true true true
false true true true true
true true true true false <- different from above
那么你可以使用这个表达式
(!a1 && a2 || a1 && !a2) && b && c
分别检查a1
和a2
。
if ((!statementA1 && statementA2 || statementA1 && !statementA2) && statementB && statementC) {
// doSomething
}
记住首字母缩略词 "Please Excuse My Dear Aunt Sally" 或 PEMDAS,它指的是括号、求幂、Multiplication/Division 和 Addition/Subtraction。在许多语言中,这就是优先顺序,从高(紧)到低(松),包括 JavaScript.
变体是 "Please Excuse My Aunt" (PEMA)。
那么请记住,在逻辑世界中,and
有点像乘法,而 or
有点像加法。这样你就可以记住 and (&&
) 比 or (||
).
绑定得更紧密
因此,如果要and
把两个条件放在一起,其中一个本身就是or
'ing两个条件,就必须把后者括起来:
a && (b || c)
如果没有括号,它将被解释为
(a && b) || c
当然,在您的特定情况下,您只需编写
就可以避免担心优先级和括号
a1 != a2 && b && c
if
语句中有一个复杂的条件,不知怎么的,它无法按照我的要求运行。
if (
(statementA1) ||
(statementA2) &&
(statementB) &&
(statementC)
) {
doSomething
}
A1
和 A2
不能同时为真(因为实际陈述的性质)。
此外,B
和 C
都必须评估 true 才能得出整体 true。
所以只有 true false true true
和 false true true true
应该 return true
;任何其他排列应该 return false
.
由于其内部复杂性(包括 Math.abs()
、A1
和 B
具有内部组合子语句),这些语句位于大括号中。
对于
a1 a2 b c result ----- ----- ----- ----- ------ true false true true true false true true true true true true true true true <- different from blow
你可以使用这个表达式
(a1 || a2) && b && c
a1
或 a2
和 b
和 c
。
if ((statementA1 || statementA2) && statementB && statementC) {
// doSomething
}
你需要括号因为 operator precedence of logical AND &&
(6) over logical OR ||
(5)
如果你有的话
a1 a2 b c result ----- ----- ----- ----- ------ true false true true true false true true true true true true true true false <- different from above
那么你可以使用这个表达式
(!a1 && a2 || a1 && !a2) && b && c
分别检查a1
和a2
。
if ((!statementA1 && statementA2 || statementA1 && !statementA2) && statementB && statementC) {
// doSomething
}
记住首字母缩略词 "Please Excuse My Dear Aunt Sally" 或 PEMDAS,它指的是括号、求幂、Multiplication/Division 和 Addition/Subtraction。在许多语言中,这就是优先顺序,从高(紧)到低(松),包括 JavaScript.
变体是 "Please Excuse My Aunt" (PEMA)。
那么请记住,在逻辑世界中,and
有点像乘法,而 or
有点像加法。这样你就可以记住 and (&&
) 比 or (||
).
因此,如果要and
把两个条件放在一起,其中一个本身就是or
'ing两个条件,就必须把后者括起来:
a && (b || c)
如果没有括号,它将被解释为
(a && b) || c
当然,在您的特定情况下,您只需编写
就可以避免担心优先级和括号a1 != a2 && b && c