【问题标题】:JavaScript false Boolean evaluates as true after assign as falseJavaScript false 布尔值在赋值为 false 后评估为 true
【发布时间】:2018-08-17 03:50:59
【问题描述】:

我的变量一直评估为真并进入 IF 块。这怎么可能?即使在我将其指定为 false 之后。

this.model.hasQ1 = false
console.log('type ', typeof this.model.hasQ1) //don't know why typeof is a string
//const test = this.model.hasQ1 === 'true' //this will error out, but shouldn't if the top is typeof is a string
if(this.model.hasQ1){ //this should be false
    console.log('hasQ1 ', this.model.hasQ1) //this gets printed anyways
}
//output: hasQ1  false

【问题讨论】:

标签: node.js typescript


【解决方案1】:

好的,toString() 技巧也是如此,它按预期进行评估。有人可以解释为什么吗?仅供参考,这是来自 Typescript 类,但我通常不必这样做。

//model was assign this way, yet appears as a string (see next line)
this.model.hasQ1 = false;

//console log of this model appears like this
....,
hasQ1: 'false' }

//This fixes the issue
if(this.model.hasQ1.toString() === 'true'){
    console.log('I should not see this')
}

【讨论】:

  • 类是什么样的?
  • 请不要发布另一个问题作为答案。
  • 也许这个类有一个 set 方法可以创建一个 .toString()
【解决方案2】:
var model = { hasQ1: null };

model.hasQ1 = false;
console.log('type ', typeof model.hasQ1) //typeof is boolean

if (model.hasQ1) { //this is false
  console.log('hasQ1 ', model.hasQ1) //this is not printed
}
//output: hasQ1  false

您必须提供该类才能找出您的代码有什么问题。

【讨论】:

    【解决方案3】:

    您可以强制将变量作为字符串进行比较以确保它有效:

    if(this.model.hasQ1.toString() == "true"){ //this should be false
        console.log('hasQ1 ', this.model.hasQ1) //this gets printed anyways
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多