如何测试变量是否等于两个值之一?

问题描述:

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

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

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

!(否定运算符)视为“不”,将||(布尔运算符)视为“或”并将&&(布尔运算符)视为“和”。见OperatorsOperator 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'或任何它需要) 。

再次,如果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') 
+2

有没有更简单的方法来做到这一点(伪代码):'if(test ===('A'||'B'))'(为了逻辑的简单,我删除了'!'对这个概念更加好奇) – 2017-01-18 21:23:01

+1

像'if(x == 2 | 3)'这样的短版本会很好。 – 2017-04-16 16:56:04

我这样做,使用jQuery

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

-1需要测试的'$ .inArray(试验,[A,B] )=== -1' – Raynos 2011-05-24 19:56:42

+2

好,公平。感谢您清理东西! – Zlatev 2011-05-24 20:30:24

+0

如果有人继续得到不希望的结果,那么你也可以检查,如果你需要得到真正的结果,测试的类型和a,b必须匹配。 – 2013-04-02 05:33:50

var test = $("#test").val(); 
if (test != 'A' && test != 'B'){ 
    do stuff; 
} 
else { 
    do other stuff; 
} 
+3

您的意思是'test!= A && test!= B' ,否则它会一直执行(除非测试== A == B) – Konerak 2011-05-24 19:33:39

+0

@Konerak,OP表示或' – Neal 2011-05-24 19:34:18

+0

@Neal:如果值'不等于2'中的任何一个, **任意一个! – Konerak 2011-05-24 19:35:28

一般来说它会是这样的:

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

你或许应该对JavaScript的逻辑运算符读了。

你用了“或”你的伪代码,但基于你的第一句话,我认为你的意思是。对此有一些困惑,因为这不是人们通常说话的方式。

你想:

var test = $("#test").val(); 
if (test !== 'A' && test !== 'B'){ 
    do stuff; 
} 
else { 
    do other stuff; 
} 

ECMA2016简短的回答,特别好检查againt当多个值:

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

这是回答问题的JavaScript方式。他并没有问及如何使用&&或||但他正在寻找允许的捷径;测试==('string1'|| string2)这将相当于(test =='string2')|| (test == string1) – Louis 2017-07-19 18:12:39

+0

下面是一个旧的但相关的参考文献; https://www.tjvantoll.com/2013/03/14/better-ways-of-comparing-a-javascript-string-to-multiple-values/ – Louis 2017-07-19 18:17:24