javascript - 如何理解 "{} == true"这个表达式?

标签 javascript

我尝试理解 doc Ecma-2627.2.12 部分后面的表达式 {} == true .

  1. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y)

ToNumber(true)的结果是1,那么

{} == 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({}) 感到困惑。

  1. If hint is "string", then

    a. Let methodNames be «"toString", "valueOf"».

  2. 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 be ToNumber(ToPrimitive({})) == ToNumber(true)?

是的,就是这样。

关于javascript - 如何理解 "{} == true"这个表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34525917/

相关文章:

javascript - 隐藏和显示错误

javascript - 使用 JS 或 jQuery 按字母顺序排列列表

javascript - var+1 和 var++ 之间的区别

javascript - 如何通过类名填充输入元素

javascript - Knockout - 无法处理绑定(bind) - 带有

javascript - 将结果输出到 div #results

javascript - 使用坐标以编程方式旋转形状

javascript - Textarea 就像 stackoverflow 中的那个

javascript - 如何向 JS 计数器添加加号?

javascript - 在 JQuery 中添加多个框阴影