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

How do I test if a variable does not equal either of two values?

提问人:daGUY 提问时间:5/25/2011 最后编辑:Ryan MdaGUY 更新时间:7/14/2022 访问量:266818

问:

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

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

如何在第 2 行编写 if 语句的条件?

JavaScript if-statement 条件语句 等于 boolean-logic

评论


答:

2赞 Z. Zlatev 5/25/2011 #1

我使用jQuery做到这一点

if ( 0 > $.inArray( test, [a,b] ) ) { ... }

评论

0赞 Bhumi Singhal 4/2/2013
如果有人继续得到不需要的结果,那么你也可以检查测试的类型和a,b也必须匹配,如果你需要得到真正的结果。
3赞 Shannon Hochkins 2/12/2015
根本不喜欢这个,它似乎更容易测试,而且读起来更好(test != 'A' && test != 'B')
0赞 AlbertVo 5/25/2011 #2
var test = $("#test").val();
if (test != 'A' && test != 'B'){
    do stuff;
}
else {
    do other stuff;
}

评论

3赞 Konerak 5/25/2011
你的意思是,否则它将始终执行(除非测试==A==B)test != A && test != B
0赞 Konerak 5/25/2011
@Neal:如果值 -> 中的任何一个,OP 希望执行代码!does NOT equal either one of two
0赞 user113716 5/25/2011
@Neal:这个答案永远是,因为总是等于一个或另一个。if()truetest
0赞 Konerak 5/25/2011
@patrick:这是不正确的,我已经在我对这个答案的第一条评论中放了一个反例......
0赞 Konerak 5/25/2011
@Jurgen:那是伪代码,读他的问题,看看他想要什么。
11赞 James Montagne 5/25/2011 #3

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

if(test != "A" && test != "B")

您可能应该阅读 JavaScript 逻辑运算符。

151赞 user166390 5/25/2011 #4

将 (否定运算符) 视为“not”,将 (boolean-or 运算符) 视为“or”,将 (boolean-and 运算符) 视为 “and”。请参阅运算符和运算符优先级!||&&

因此:

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

但是,使用德摩根定律,它可以写成:

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

a上面可以是任何表达式(例如或任何它需要的东西)。btest == 'B'

再一次,如果 和 是表达式,请注意第一种形式的扩展: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')

评论

3赞 Ivan Durst 1/19/2017
有没有更短的方法可以做到这一点(伪代码):(为了逻辑简单,我删除了,我对这个概念更好奇)if(test === ('A' || 'B'))!
3赞 Sodj 4/17/2017
像这样的简短版本会很好。if(x == 2|3)
0赞 sophistihip 5/25/2011 #5

你在伪代码中使用了“或”这个词,但根据你的第一句话,我认为你的意思是和。对此有一些困惑,因为这不是人们通常说话的方式。

你想要:

var test = $("#test").val();
if (test !== 'A' && test !== 'B'){
    do stuff;
}
else {
    do other stuff;
}
80赞 CESCO 5/24/2017 #6

ECMA2016答案,在检查多个值时尤其好:

if (!["A","B", ...].includes(test)) {}

评论

6赞 Louis 7/20/2017
这是回答问题的 JavaScript 方式。他没有问如何使用&&或||但他正在寻找一条允许的捷径;test == ( 'string1' || string2) 等价于 (test == 'string2') ||(测试 == string1)
0赞 Louis 7/20/2017
这是一个古老但相关的参考资料;tjvantoll.com/2013/03/14/......
0赞 ikoza 4/28/2023
这是niiiice,谢谢。从来没有想过 .includes( ) 这样。有点想“反向”使用它,因为我从根本上考虑了变量及其值之间的关系。平等意味着双向包容,美妙的:)
2赞 Unmitigated 8/18/2021 #7

对于经常检查的大量值,检查该值是否存在于 Set 中可能更有效。

const values = new Set(["a", "b"]);
if(!values.has(someValue)){
    // do something
} else {
    // do something else
}