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

IT技术 javascript if-statement conditional-statements equals boolean-logic
2021-01-19 23:18:03

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

var test = $("#test").val();
如果(测试不等于 A 或 B){
    做东西;
}
别的 {
    做其他事情;
}

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

6个回答

!(否定运算符)视为“非”,||(布尔或运算符)视为“或”,将&&(布尔与运算符)视为“与”。请参阅运算符运算符优先级

因此:

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

然而,使用德摩根定律,它可以写成:

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

aand babove 可以是任何表达式(例如test == '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')
有没有更短的方法可以这样做(伪代码):(为了逻辑简单,我if(test === ('A' || 'B'))删除了!,我对这个概念更好奇)
2021-03-31 23:18:03
if(x == 2|3)这样的简短版本会很好。
2021-04-09 23:18:03

ECMA2016 最短答案,在检查多个值时特别好:

if (!["A","B", ...].includes(test)) {}
这是回答问题的 JavaScript 方式。他不是在问如何使用 && 或 || 但他正在寻找一条允许的捷径;test == ( 'string1' || string2) 等价于 (test == 'string2') || (测试 == 字符串 1)
2021-03-13 23:18:03
这是一个古老但相关的参考资料;tjvantoll.com/2013/03/14/…
2021-03-19 23:18:03

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

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

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

我使用 jQuery 做到这一点

if ( 0 > $.inArray( test, [a,b] ) ) { ... }
如果有人继续得到不想要的结果,那么您还可以检查测试的 typeof 和 a, b 是否也必须匹配,如果您需要得到 true 作为结果。
2021-04-03 23:18:03
根本不喜欢这个,它似乎更容易测试(test != 'A' && test != 'B')并且读起来更好
2021-04-10 23:18:03
var test = $("#test").val();
if (test != 'A' && test != 'B'){
    do stuff;
}
else {
    do other stuff;
}
@Jurgen:那是伪代码,请阅读他的问题以了解他想要什么。
2021-03-14 23:18:03
你的意思是test != A && test != B,否则它会一直执行(除非测试 == A == B)
2021-03-19 23:18:03
@Neal:if()这个答案中的永远是true因为test永远等于一个或另一个。
2021-03-22 23:18:03
@patrick:那是不正确的,我已经在我对这个答案的第一条评论中放了一个反例......
2021-04-05 23:18:03
@Neal:如果值does NOT equal either one of two->,OP 想要执行代码
2021-04-06 23:18:03