daG*_*GUY 43 javascript boolean-logic if-statement equals conditional-statements
我想编写一个if/else语句来测试文本输入的值是否不等于两个不同值中的任何一个.像这样(借口我的伪英语代码):
var test = $("#test").val(); if (test does not equal A or B){ do stuff; } else { do other stuff; }
如何在第2行写if语句的条件?
小智 117
将!
(否定运算符)视为"不",||
(布尔运算符或运算符)为"或",&&
(布尔运算符和运算符)为"和".请参阅运算符和运算符优先级.
从而:
if(!(a || b)) {
// means neither a nor b
}
Run Code Online (Sandbox Code Playgroud)
但是,使用De Morgan定律,它可以写成:
if(!a && !b) {
// is not a and is not b
}
Run Code Online (Sandbox Code Playgroud)
a
和b
以上可以是任何表达式(如test == 'B'
或任何它需要).
再一次,if test == 'A'
和test == 'B'
是表达式,请注意第一种形式的扩展:
// if(!(a || b))
if(!((test == 'A') || (test == 'B')))
// or more simply, removing the inner parenthesis as
// || and && have a lower precedence than comparison and negation operators
if(!(test == 'A' || test == 'B'))
// and using DeMorgan's, we can turn this into
// this is the same as substituting into if(!a && !b)
if(!(test == 'A') && !(test == 'B'))
// and this can be simplified as !(x == y) is the same as (x != y)
if(test != 'A' && test != 'B')
Run Code Online (Sandbox Code Playgroud)
CES*_*SCO 30
ECMA2016最短的答案,特别适合检查多个值:
if (!["A","B", ...].includes(test)) {}
Run Code Online (Sandbox Code Playgroud)
一般来说,它会是这样的:
if(test != "A" && test != "B")
Run Code Online (Sandbox Code Playgroud)
您应该阅读JavaScript逻辑运算符.
归档时间: |
|
查看次数: |
169585 次 |
最近记录: |