我知道在 JavaScript 中你可以写:
if (A && B) { do something }
但是我如何实现 OR,例如:
if (A OR B) { do something }
我知道在 JavaScript 中你可以写:
if (A && B) { do something }
但是我如何实现 OR,例如:
if (A OR B) { do something }
只需使用逻辑“或”运算符,即||
.
if (A || B)
值得注意的是,如果 BOTH和are||
也会返回。true
A
B
true
在 JavaScript 中,如果您正在寻找A
or B
,但不是两者,您需要执行类似以下操作:
if( (A && !B) || (B && !A) ) { ... }
if (A || B) { do something }
||
是 or 运算符。
if(A || B){ do something }
这是我的例子:
if(userAnswer==="Yes"||"yes"||"YeS"){
console.log("Too Bad!");
}
这表示如果答案是 Yes Yes 或 Yes,那么同样的事情将会发生
也可以使用正则表达式:
var thingToTest = "B";
if (/A|B/.test(thingToTest)) alert("Do something!")
这是一般正则表达式的示例:
var myString = "This is my search subject"
if (/my/.test(myString)) alert("Do something here!")
这将在变量“myString”中查找“my”。您可以直接用字符串代替“myString”变量。
作为额外的奖励,您还可以将不区分大小写的“i”和全局“g”添加到搜索中。
var myString = "This is my search subject"
if (/my/ig.test(myString)) alert("Do something here");
如果我们要提到正则表达式,我们不妨提一下switch
语句。
var expr = 'Papayas';
switch (expr) {
case 'Oranges':
console.log('Oranges are $0.59 a pound.');
break;
case 'Mangoes':
case 'Papayas': // Mangoes or papayas
console.log('Mangoes and papayas are $2.79 a pound.');
// expected output: "Mangoes and papayas are $2.79 a pound."
break;
default:
console.log('Sorry, we are out of ' + expr + '.');
}
你可以使用喜欢
if(condition1 || condition2 || condition3 || ..........)
{
enter code here
}
OR(||)
在 if 条件和符号 is中使用运算符需要不止一个条件语句||
。
if(condition || condition){
some stuff
}