我想写一个if/else语句来测试文本输入的值是否等于两个不同值中的任何一个。这样的(请原谅我的伪英文代码):如何测试变量是否等于两个值之一?
var test = $("#test").val(); if (test does not equal A or B){ do stuff; } else { do other stuff; }
我怎样写的条件第2行的if语句?
我想写一个if/else语句来测试文本输入的值是否等于两个不同值中的任何一个。这样的(请原谅我的伪英文代码):如何测试变量是否等于两个值之一?
var test = $("#test").val(); if (test does not equal A or B){ do stuff; } else { do other stuff; }
我怎样写的条件第2行的if语句?
将!
(否定运算符)视为“不”,将||
(布尔运算符)视为“或”并将&&
(布尔运算符)视为“和”。见Operators和Operator 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')
一般来说它会是这样的:
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)) {}
有没有更简单的方法来做到这一点(伪代码):'if(test ===('A'||'B'))'(为了逻辑的简单,我删除了'!'对这个概念更加好奇) – 2017-01-18 21:23:01
像'if(x == 2 | 3)'这样的短版本会很好。 – 2017-04-16 16:56:04