JavaScript 中的强制

Coercion in JavaScript

我想知道关于强制的一些事情。

当你这样做时:

1 == true // true

哪一个被逼成了哪一个?是左边的还是右边的?

当你

undefined == null // true

它是如何工作的? 它尝试以什么顺序转换它? 通过实例:

1)    String(undefined) == String(null) // false
2)    Number(undefined) == Number(null) // false
3)    Boolean(undefined) == Boolean(null) // true

它是否首先尝试强制转换左侧操作数?那么对吗?然后两者都有?

编辑: 如评论中所述: "not a duplicate. While both questions are about type coercion, this one asks which operand get coerced into the other. The other one is about the source of truth when evaluating the coerced types"

该过程在 7.2.12 Abstract Equality Comparison:

中有描述

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

  1. If Type(x) is the same as Type(y), then return the result of performing Strict Equality Comparison x === y.

  2. If x is null and y is undefined, return true.

  3. If x is undefined and y is null, return true.

  4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

  5. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.

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

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

  8. If Type(x) is either String, Number, or Symbol and Type(y) is Object, then return the result of the comparison x == ToPrimitive(y).

  9. If Type(x) is Object and Type(y) is either String, Number, or Symbol, then return the result of the comparison ToPrimitive(x) == y.

  10. Return false.

因此,与其先强制一侧,然后强制另一侧,或类似的东西,不如解释器遍历上面的列表,直到找到匹配条件,然后执行结果命令,这可能只涉及强制左侧,或仅右侧(很少,两者都达到,以防达到递归命令,例如使用 true == '1',这将满足条件 8,变成 1 == '1',满足条件 6 和变为 1 == 1,满足条件 3 并解析为 true)