143

我知道在 JavaScript 中你可以写:

if (A && B) { do something }

但是我如何实现 OR,例如:

if (A OR B) { do something }
4

11 回答 11

287

只需使用逻辑“或”运算符,即||.

if (A || B)
于 2010-03-02T14:39:57.097 回答
94

值得注意的是,如果 BOTH和are||也会返回。trueABtrue

在 JavaScript 中,如果您正在寻找Aor B但不是两者,您需要执行类似以下操作:

if( (A && !B) || (B && !A) ) { ... }
于 2010-03-02T14:50:08.850 回答
16

使用||运算符

于 2010-03-02T14:39:49.593 回答
15
if (A || B) { do something }
于 2010-03-02T14:39:42.727 回答
12

||是 or 运算符。

if(A || B){ do something }
于 2010-03-02T14:40:09.930 回答
10

这是我的例子:

if(userAnswer==="Yes"||"yes"||"YeS"){
 console.log("Too Bad!");   
}

这表示如果答案是 Yes Yes 或 Yes,那么同样的事情将会发生

于 2014-12-30T20:41:06.673 回答
2

也可以使用正则表达式

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");

于 2019-03-21T12:31:25.820 回答
1

如果我们要提到正则表达式,我们不妨提一下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 + '.');
}

于 2020-01-08T01:38:22.667 回答
0

你可以使用喜欢

if(condition1 || condition2 || condition3 || ..........)
{       
     enter code here
}
于 2019-01-29T17:54:43.633 回答
0

OR(||)在 if 条件和符号 is中使用运算符需要不止一个条件语句||

if(condition || condition){ 
   some stuff
}
于 2017-04-25T04:21:17.987 回答
-1

只需使用||

if (A || B) { your action here }

注意:带字符串和数字。它更复杂。

检查以深入了解:

于 2014-06-27T16:02:55.237 回答