JS类型强制如何工作?
我正在学习 ==
与 ===
并遇到此answer 对理解这个概念非常有帮助。但是我想知道其中一个例子:
I'm learning about ==
vs. ===
and came across this answer which was very helpful in understanding the concept. However I wondered about one of the examples:
'0' == false // true
这可能有意义,因为 ==
不会检查类型。但后来我在控制台中尝试了一些可能的强制措施,发现了以下内容:
This might make sense, since ==
doesn't check for type. But then I tried some possible coercions in the console and found the following:
Boolean('0') // true
String(false) // "false"
我原以为 '0'== false
具有与'0'=== String(false)
相同的真值,但似乎没有是这样的。
I would have thought '0' == false
has the same truth value as '0' === String(false)
, but that doesn't seem to be the case.
那么强制如何实际起作用?是否有一种我缺少的基本类型?
So how does the coercion actually work? Is there a more basic type I'm missing?
0
是包含字符 0 的字符串,不数字值 0
。评估为 false
的唯一字符串类型值为。
"0"
is a string containing the character 0, it is not the numeric value 0
. The only string-type value which evaluates to false
is ""
.
0
truthy 。
ECMAScript 262规范的第9.2节定义了不同类型如何转换为布尔值:
Section 9.2 of the ECMAScript 262 specification defines how different types are converted to Boolean:
Argument Type Result
Undefined false
Null false
Boolean The result equals the input argument (no conversion).
Number The result is false if the argument is +0, −0, or NaN; otherwise the
result is true.
String The result is false if the argument is the empty String (its length is
zero); otherwise the result is true.
Object true
然而,只有在使用 === 。
当使用布尔值('0')
时你'将值'0'
转换为布尔值(与使用 !!'0'
相同)。当松散地比较'0'
与 false
时,布尔值将转换为数字(如定义的这里)。 false
,当转换为数字时,变为 0
。这意味着最终计算是'0'== 0
,相当于 true
。
When using Boolean('0')
you're converting the value '0'
to Boolean (which is the same as using !!'0'
). When loosely comparing '0'
with false
, the Boolean value is converted to a number (as defined here). false
, when converted to a number, becomes 0
. This means the final calculation is '0' == 0
which equates to true
.
总结上述ECMAScript规范链接部分的相关部分:
To summarise the relevant part of the linked section of the ECMAScript specification above:
- 让 x =
'0'
和 y =false
。 - 检查 y 的类型是否为布尔值。
- 如果为true,则将 y 转换为数字。
- 将 x 与 y 的等效数字进行比较。
- Let x =
'0'
and y =false
. - Check if the type of y is Boolean.
- If true, convert y to a number.
- Compare x to the numeric equivalent of y.
在我们的例子中,JavaScript的实现方式是:
In our case, a JavaScript implementation of this would be:
var x = '0', // x = "0"
y = false; // y = false
if (typeof y === "boolean") {
y = +y; // y = 0
}
console.log( x == y ); // "0" == 0
-> true