我想编写一个 if/else 语句来测试文本输入的值是否不等于两个不同值中的任何一个。像这样(请原谅我的伪英文代码):
var test = $("#test").val(); if (test does not equal A or B){ do stuff; } else { do other stuff; }
第 2 行的 if 语句的条件怎么写?
最佳答案
将!
(否定运算符)视为“非”,将||
( bool 或运算符)视为“或”,将&&
( bool 与运算符)作为“和”。参见 Operators和 Operator Precedence .
因此:
if(!(a || b)) {
// means neither a nor b
}
但是,使用 De Morgan's Law ,可以写成:
if(!a && !b) {
// is not a and is not b
}
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')
关于javascript - 如何测试变量是否不等于两个值中的任何一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6115801/