我想编写一个 if/else 语句来测试文本输入的值是否不等于两个不同值中的任何一个。像这样(原谅我的伪英文代码):
var test = $("#test").val(); 如果(测试不等于 A 或 B){ 做东西; } 别的 { 做其他事情; }
如何为第 2 行的 if 语句编写条件?
我想编写一个 if/else 语句来测试文本输入的值是否不等于两个不同值中的任何一个。像这样(原谅我的伪英文代码):
var test = $("#test").val(); 如果(测试不等于 A 或 B){ 做东西; } 别的 { 做其他事情; }
如何为第 2 行的 if 语句编写条件?
将!
(否定运算符)视为“非”,||
(布尔或运算符)视为“或”,将&&
(布尔与运算符)视为“与”。请参阅运算符和运算符优先级。
因此:
if(!(a || b)) {
// means neither a nor b
}
然而,使用德摩根定律,它可以写成:
if(!a && !b) {
// is not a and is not b
}
a
and b
above 可以是任何表达式(例如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')
ECMA2016 最短答案,在检查多个值时特别好:
if (!["A","B", ...].includes(test)) {}
一般来说,它会是这样的:
if(test != "A" && test != "B")
您可能应该阅读 JavaScript 逻辑运算符。
我使用 jQuery 做到这一点
if ( 0 > $.inArray( test, [a,b] ) ) { ... }
var test = $("#test").val();
if (test != 'A' && test != 'B'){
do stuff;
}
else {
do other stuff;
}