这个问题在这里已有答案:
可能我很困惑或者其他什么,但我无法理解这个愚蠢的场景。
if("true"){
console.log("Above is true");
}
else{
console.log("Above is false");
}
在上面的情况下,控制台很好地打印Above is true
。这是完全有道理的。但是当我这样做的时候:
if("true" == true){
console.log("Above is true");
}
else{
console.log("Above is false");
}
我看到Above is false
正在控制台中打印出来。
我在这里使用松散的相等运算符,甚至在强制后true
将转换为"true"
所以它应该打印Above is true
但不是。我错过了什么?
看看这篇文章https://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/
//EQUALITY CHECK...
"true" == true;
//HOW IT WORKS...
//boolean is converted using toNumber
"true" == 1;
//string is converted using toNumber
NaN == 1; //false!
“如果其中一个操作数是布尔值,则布尔操作数如果为真,则转换为1,如果为假,则转换为+0。”
true == "true"; //false
true == "1"; //true
false == "false"; //false
false == ""; //true
false == "0"; //true