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

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)

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')
Run Code Online (Sandbox Code Playgroud)

  • 像 `if(x == 2|3)` 这样的简短版本会很好。 (3认同)
  • 有没有更简单的方法这样做(伪代码):`if(test ===('A'||'B'))`(为了逻辑简单,我删除了`!`,我更多好奇这个概念) (2认同)

CES*_*SCO 30

ECMA2016最短的答案,特别适合检查多个值:

if (!["A","B", ...].includes(test)) {}
Run Code Online (Sandbox Code Playgroud)

  • 这是回答问题的JavaScript方法.他没有询问如何使用&&或|| 但他正在寻找一条允许的捷径; test ==('string1'|| string2)等同于(test =='string2')|| (test == string1) (4认同)

Jam*_*gne 8

一般来说,它会是这样的:

if(test != "A" && test != "B")
Run Code Online (Sandbox Code Playgroud)

您应该阅读JavaScript逻辑运算符.