如果[重复]则将字符串等于true

问题描述 投票:1回答:2

这个问题在这里已有答案:

可能我很困惑或者其他什么,但我无法理解这个愚蠢的场景。

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但不是。我错过了什么?

javascript
2个回答
4
投票

看看这篇文章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!

0
投票

“如果其中一个操作数是布尔值,则布尔操作数如果为真,则转换为1,如果为假,则转换为+0。”

true == "true"; //false
true == "1"; //true
false == "false"; //false
false == ""; //true
false == "0"; //true

Further readings on here.

© www.soinside.com 2019 - 2024. All rights reserved.