我尝试理解 doc Ecma-262
的 7.2.12
部分后面的表达式 {} == true
.
- If Type(y) is Boolean, return the result of the comparison
x == ToNumber(y)
ToNumber(true)
的结果是1
,那么
{} == 1
- If Type(x) is Object and Type(y) is either String, Number, or Symbol, then return the result of the comparison
ToPrimitive(x) == y
.
我现在对 ToPrimitive({})
感到困惑。
If hint is "string", then
a. Let methodNames be «"toString", "valueOf"».
Else,
a. Let methodNames be «"valueOf", "toString"».
ToPrimitive({})
是否应解释为 {}.toString()
或 {}.valueOf()
?
假设调用了toString()
。
If Type(x) is String and Type(y) is Number, return the result of the comparison
ToNumber(x) == y
那么 {} == true
可能是 ToNumber(ToPrimitive({})) == ToNumber(true)
?
最佳答案
spec说:
When
ToPrimitive
is called with no hint, then it generally behaves as if the hint were Number.
因此,根据ToPrimitive
算法,首先调用valueOf
。但由于它返回一个对象,而不是原始值,所以第二个将调用 toString,它返回一个字符串。
So
{} == true
could beToNumber(ToPrimitive({})) == ToNumber(true)
?
是的,就是这样。
关于javascript - 如何理解 "{} == true"这个表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34525917/