[英]Why false == “false” is false?
I am still learning the basics of javaScript and I don't understand why this happens. 我还在学习javaScript的基础知识,我不明白为什么会这样。
Having type coercion false == "false"
would be converted into: 类型强制
false == "false"
将被转换为:
false == false //true
or 要么
"false" == "false" //true
So, why false == "false"
is false? 那么,为什么
false == "false"
是假的?
You've misunderstood the type conversion rules . 您误解了类型转换规则 。
false
doesn't get converted to a string before comparison. 在比较之前,
false
不会转换为字符串。
If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
如果Type(x)是布尔值,则返回比较结果ToNumber(x)== y。
false
is converted to a number, which gives: false
被转换为数字,这给出了:
+0 == "false"
… then … … 然后 …
If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
如果Type(x)为Number且Type(y)为String,则返回比较结果x == ToNumber(y)。
… "false"
is converted to a number, which gives: ...
"false"
转换为数字,它给出:
+0 == NaN
… which is false. ......这是假的。
The answer is because "false" is a string (as Gerardo Furado pointed out in the comments), the test you are making is equivalent to false = "hello". 答案是因为“false”是一个字符串(正如Gerardo Furado在评论中指出的那样),你所做的测试等同于false =“hello”。
Javascript does not look at the word in the string to determine if it is a boolean and then try to get the value from that. Javascript不会查看字符串中的单词来确定它是否是布尔值,然后尝试从中获取值。
Note: 注意:
In general in javascript it is now preferred that you use the === operator, to avoid all of this. 通常在javascript中,现在首选使用===运算符,以避免所有这些。
false == "false" // false
因为,布尔值false被转换为0,因此,我们将0与“false”进行比较,输出为false
These are different kind of items. 这些是不同类型的物品。
"string"
and boolean
. "string"
和boolean
。
So: 所以:
false.toString() == "false"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.