为什么一个对象大于/小于或等于另一个对象? [英] Why is an object greater/less than or equal to a different object?
问题描述
这可能只是JavaScript的怪癖,但我很好奇是否有人知道为什么会发生这种情况:
This might just be a weird quirk of JavaScript, but I'm curious if anyone knows why this happens:
({}< = {})=>是
({}> = {})=>是
({} == {})=>错误
({} === {})=>错误
({}> {})=>错误
({}< {})=>错误
鉴于其他两个均为假,为什么前两个为真?
Why are the first two true given that all the others are false?
我认为可能是在比较之前将对象转换为数字,但是...
I thought it may be casting the objects to numbers before comparing, but...
Number({})> = Number({})=>错误
推荐答案
使用<
/< =
/>
/ES5中的> =
运算符使用抽象关系比较算法" ,这是一种在比较类型之前将其强制转换的好方法.当 {}
与 [[ToPrimitive]]
强制转换时,它会退回到 toString()
方法,该方法返回"[object Object]"
.因为小于/大于运算符的equals-variant首先检查相等性,并且字符串相等,所以检查成功.对于非相等检查变体,它失败了,因为字符串相等.
Using the <
/<=
/>
/>=
operators in ES5 uses the Abstract Relational Comparison Algorithm, which is a fancy way of saying it coerces the types before comparing them. When {}
is coerced with [[ToPrimitive]]
, it falls back to the toString()
method, which returns "[object Object]"
for both. Because the equals-variants of the less than/greater than operators check equality first, and the strings are equal, the check succeeds. It fails for the non-equality-checking variants because, well, the strings are equal.
==
doesn't use the same coercion algorithm, it uses the Abstract Equality Comparison Algorithm. The first thing this algorithm checks is if the types are the same -- which they are, of course, for two bare objects. Therefore the algorithm proceeds with the first step, and goes down to check f:
如果x和y指向同一个对象,则返回true.否则,返回false.
Return true if x and y refer to the same object. Otherwise, return false.
每次使用 {}
都会创建一个新对象,因此此检查失败,结果为false.
Each usage of {}
creates a new object, so this check fails and the result is false.
===
类似,除了没有强制步骤.它在步骤7 处失败,该步骤使用相同的方法语言作为AECA的子步骤f.
===
is similar, except there is no coercion step. It fails at step 7, which uses the same language as substep f of the AECA.
tl; dr:> =
/< =
以不同于 ==
/ ===的方式强制转换
.
tl;dr: >=
/ <=
coerce in a different way than ==
/ ===
.
这篇关于为什么一个对象大于/小于或等于另一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!