【问题标题】:Check true or false in JavaScript在 JavaScript 中检查真假
【发布时间】:2021-04-20 22:08:53
【问题描述】:

所以我有这个代码:

function step3() {
    //finds both answers
    answer1 = top1 / (2*a);
    answer2 = top2 / (2*a);
    console.log(answer1 + " " + answer2);
    solutions = isNaN(answer1)
    console.log(solutions)
    if (solutions = true) {
        console.log("no real sol")}
    step4()
}

当我运行它时,如果 answer1 是 NaN,它会打印 true,但每次它都不会打印出真正的 sol。为什么这样做?我认为只有在解决方案为真时才会这样做。

【问题讨论】:

  • 您不需要为truefalse 明确检查布尔值。 if(solutions) 就是你所需要的。
  • if (solutions = true) 不检查solutions 是否等于真,它是设置 solutions 等于true。你想要if (solutions === true)(或==,这取决于你想要什么类型的相等检查。
  • 除了@ScottMarcus 的评论之外,您还使用了赋值运算符 (=) 而不是相等运算符 (==)。
  • 了解======之间的区别

标签: javascript


【解决方案1】:

您正在使用赋值运算符= 而不是比较运算符=====,所以solutions = true 所做的是导致solutions 变为true,而不管它在前一行是什么.

而且,要检查布尔变量,您不需要将其与 true 进行比较,因为 if 语句将始终寻找您传递的条件的“真实性”,因此您的代码应该是:

function step3() {
    //finds both answers
    answer1 = top1 / (2*a);
    answer2 = top2 / (2*a);
    console.log(answer1 + " " + answer2);
    solutions = isNaN(answer1)
    console.log(solutions)
    if (solutions) {
        console.log("no real sol");
    }
    step4()
}

【讨论】:

    【解决方案2】:

    在 JS 中,用于检查两个值是否相等的比较运算符是 ==,但您只有一个 = 将值设置为 true,只需使用

    if(isNan(answer1)) { /*your code*/ }
    

    为了避免混淆

    【讨论】:

      【解决方案3】:

      我不知道您的所有代码,但您在解决方案和真值之间只有一个等号。在比较中,我们应该使用“==”而不是“=”

      function step3() {
          //finds both answers
          answer1 = top1 / (2*a);
          answer2 = top2 / (2*a);
          console.log(answer1 + " " + answer2);
          solutions = isNaN(answer1)
          console.log(solutions)
          if (solutions == true) {
              console.log("no real sol")}
          step4()
      }
      

      【讨论】:

        【解决方案4】:

        你有三个选择。

        1. 如果(解决方案)
        2. 如果(解决方案 === 真)
        3. 如果(解决方案 == true)

        前面的问题有很多关于三种可能性的信息...... boolean in an if statement

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-11-23
          • 1970-01-01
          • 2018-06-04
          • 2014-10-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-27
          相关资源
          最近更新 更多