在if语句中使用多个条件

时间:2019-04-08 17:53:43

标签: javascript

如何在if语句中使用多个条件?

outputDevice

function testNum(a) { if (a == (1 || 2 || 3)) { return "is 1, 2, or 3"; } else { return "is not 1, 2, or 3"; } } console.log(testNum(1)); // returns "is 1, 2, or 3" console.log(testNum(2)); // returns "is not 1, 2, or 3" console.log(testNum(3)); // returns "is not 1, 2, or 3"testNum(2)应该testNum(3)但不是。

6 个答案:

答案 0 :(得分:8)

在这种特定情况下,您甚至可以使用数组和Array#includes方法进行检查。

if ([1, 2, 3].includes(a)) {
  // your code
}

function testNum(a) {
  if ([1, 2, 3].includes(a)) {
    return "is 1, 2, or 3";
  } else {
    return "is not 1, 2, or 3";
  }
}
console.log(testNum(1));
console.log(testNum(2));
console.log(testNum(4));
console.log(testNum(3));

仅供参考::在您当前的代码中,(1 || 2 || 3)的结果为1(因为1为真),实际上a == (1 || 2 || 3)的结果为a == 1。正确的方法是用||(或)分隔每个条件,例如 a == 1 || a == 2 || a ==3

有关更多详细信息,请访问MDN documentation of Logical operators

答案 1 :(得分:6)

您不能有这样的||。您使用的方法不正确。您应该使用:

function testNum(a) {
  if (a == 1 || a == 2 || a == 3) {
    return "is 1, 2, or 3";
  } else {
    return "is not 1, 2, or 3";
  }
}

console.log(testNum(1));
console.log(testNum(2));
console.log(testNum(3));

答案 2 :(得分:4)

您的操作符放置不正确:

function testNum(a) {
    if (a == 1 || a == 2 || a == 3) {
        return "is 1, 2, or 3";
    } else {
        return "is not 1, 2, or 3";
    }
}

之前,您要测试a是否等于1 || 2 || 3,得出1†。因此,您只是在检查a == 1,这不是您想要的!

†本质上,当您像这样将“或”串在一起时,将返回第一个真实值。例如,您可以自己断言:0 || False || 5给出5

答案 3 :(得分:0)

您可以尝试使用合格值列表,并检查查找值是否属于该值:

function testNum(a) {
    var candidates = [1, 2, 3];
    if (candidates.indexOf(a) != -1) {
        return "is 1, 2, or 3";
    } else {
        return "is not 1, 2, or 3";
    }
}

console.log(testNum(1)); // returns "is 1, 2, or 3"
console.log(testNum(2)); // returns "is not 1, 2, or 3"
console.log(testNum(3));
console.log(testNum(4));

答案 4 :(得分:0)

您可以

    if (a == 1 || a == 2 || a == 3) {

    if ([1, 2, 3].includes(a)) {

当要测试的值更多时,这将更加方便。如果要与古代浏览器兼容,则必须这样编写

    if ([1, 2, 3].indexOf(a) >= 0) {

看起来很丑。

答案 5 :(得分:0)

由于在此处执行逻辑或运算而未得到预期结果的原因。

根据MDN网络: 逻辑OR(||)expr1 || expr2如果expr1可以转换为true,则返回expr1;否则,返回expr2。

评估

(1 || 2 || 3)并得出1的运算结果。您可以通过将(1 || 2 || 3)粘贴到Chrome调试器等中来检查结果。

因此,在所有情况下第一个数字均为1时,表达式结果也为1。您可以按照其他人建议的方式更改表达式以获取所需的输出。