【问题标题】:How do I use a variable with a boolean value as a condition in an IF statement in JavaScript? [duplicate]如何在 JavaScript 的 IF 语句中使用具有布尔值的变量作为条件? [复制]
【发布时间】:2012-01-09 19:40:46
【问题描述】:

如何在 JavaScript 的 IF 语句中使用具有布尔值的变量作为条件?

patt1 = new RegExp ("time");

var searchResult = (patt1.test("what time is it" )); // search for the word time in the string
                                                 // and return true or false

If (searchResult = true) // what is the right syntax for the condition?
{
    document.write("Word is in the statement");
    document.write("<br />");
}

【问题讨论】:

  • 您只能使用变量作为“条件”:if (searchResult),如果您想使用该语法,使用一个 = 将不起作用,因为 = 运算符用于 java 和 jscript 中的赋值你应该使用if (searchResult == true)

标签: javascript if-statement boolean


【解决方案1】:

直接使用该值,Javascript 将确定它是否真实。

if (searchResult) {
  // It's truthy
  ...
}

原始示例中的问题是您使用的是searchResult = true。这不是一个简单的条件检查,而是一个赋值,它产生一个值,然后作为条件检查。这大致相当于说以下内容

searchResult = true;
if (true) { 
  ...
}

在 Javascript 中,= 运算符有多种使用方式

  • =这是用于赋值的
  • == 用于强制相等性检查
  • === 这用于严格的相等检查

【讨论】:

  • 这里更重要的一点是,他的代码不起作用的原因是因为他使用=true 分配给searchResult,而不是使用== 比较它们。跨度>
  • @JustinSatyr 更新答案更完整
  • 还有If 而不是if
  • 感谢大家的帮助,最后才开始编码,我想我仍然在犯基本错误。
【解决方案2】:
if (searchResult == true) {
...
}

这是一个测试。

短版:

if (searchResult) {
...
}

【讨论】:

    【解决方案3】:
    if (searchResult) is the same as if(searchResult == true)
    if (!searchResult) is the same as if(searchResult == false)
    

    【讨论】:

      猜你喜欢
      • 2022-10-08
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      • 2018-02-01
      • 2018-06-16
      • 2018-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多