我的变量保持评估为真,并进入IF块。这怎么可能?即使我将其指定为假。
{{1}}
答案 0 :(得分:0)
你可以强制将变量作为字符串进行比较,以确保其有效:
if(this.model.hasQ1.toString() == "true"){ //this should be false
console.log('hasQ1 ', this.model.hasQ1) //this gets printed anyways
}
答案 1 :(得分:0)
好的,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')
}
答案 2 :(得分:0)
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
您必须提供课程才能弄清楚您的代码有什么问题。