javascript - 如何测试变量是否不等于两个值中的任何一个?

标签 javascript if-statement conditional-statements equals boolean-logic

我想编写一个 if/else 语句来测试文本输入的值是否不等于两个不同值中的任何一个。像这样(请原谅我的伪英文代码):

var test = $("#test").val();
if (test does not equal A or B){
    do stuff;
}
else {
    do other stuff;
}

第 2 行的 if 语句的条件怎么写?

最佳答案

!(否定运算符)视为“非”,将||( bool 或运算符)视为“或”,将&& ( bool 与运算符)作为“和”。参见 OperatorsOperator Precedence .

因此:

if(!(a || b)) {
  // means neither a nor b
}

但是,使用 De Morgan's Law ,可以写成:

if(!a && !b) {
  // is not a and is not b
}

ab 可以是任何表达式(例如 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/

相关文章:

javascript - 如何知道我的文本在 DIV 中包裹了多少行

python - 为什么 if x,y : raise a SyntaxError?

Java 石头纸游戏循环次数过多

r - 不要选择 NA 值

python - 为什么在 Pylint 认为不正确的条件值中使用 len(SEQUENCE)?

ios - SwiftUI - 根据条件添加导航栏按钮

javascript - 检查空属性jquery

javascript - if 语句中的 else block 永远不会到达

javascript - 当追加子节点时,它抛出错误 "Property ' appendChild' does not believe on type 'NodeListOf<Element>' 。”

JAVA 为什么这个缩短版本不能工作?