【问题标题】:if statement with multiple or conditions returning wrong value具有多个 or 条件的 if 语句返回错误值
【发布时间】:2021-12-26 02:27:19
【问题描述】:

我很确定我在这里遗漏了一些基本的东西,但是我在 if 语句中使用多个 or|| 运算符时遇到了麻烦。

由于某种原因,if 语句没有捕获 name 变量:

testword = "billy"

if ((testword != "billy") ||
    (testword != "tom") ||
    (testword != "sara") ||
    (testword != "michael")) {
console.log("none of the names match")
} else {
console.log("name found!")
}

当我尝试这个时,我得到none of the names match,而我应该得到name found!

【问题讨论】:

  • 这是一个常见的错误。你需要一步一步地思考。第一个将返回 false。第二个将返回 true。如果单词是tom,它将在第一个条件下返回true,在第二个条件下返回false。您在这里需要 && 运算符而不是 ||

标签: javascript if-statement


【解决方案1】:

你的逻辑有点复杂

一种更简单的编写和理解方法是将所有这些名称放入一个数组中,然后查看该数组是否包含测试字。这只是一个布尔测试

const testword = "billy",
  words = ["billy", "tom", "sara", "michael"]

if (words.includes(testword)) {
  console.log("name found!")
} else {
  console.log("none of the names match")
}

【讨论】:

    【解决方案2】:

    or 运算符在任何条件不等于 testword 时执行为 true,从而记录 none of the names match

    但是,您可以尝试将代码更改为

    testword = "billy"
    names = ['billy','tom','sara','michael',]
    
    if (names.indexOf(testword) != -1) {
    console.log("name found!")
    } else {
    console.log("none of the names match")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-20
      • 2013-04-18
      • 1970-01-01
      • 2014-08-13
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多