最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is an object greaterless than or equal to a different object? - Stack Overflow

programmeradmin1浏览0评论

This might just be a weird quirk of JavaScript, but I'm curious if anyone knows why this happens:

({} <= {}) => true

({} >= {}) => true

({} == {}) => false

({} === {}) => false

({} > {}) => false

({} < {}) => false

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({}) => false

This might just be a weird quirk of JavaScript, but I'm curious if anyone knows why this happens:

({} <= {}) => true

({} >= {}) => true

({} == {}) => false

({} === {}) => false

({} > {}) => false

({} < {}) => false

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({}) => false

Share Improve this question asked Apr 28, 2016 at 22:20 Bryan DowningBryan Downing 15.5k3 gold badges42 silver badges61 bronze badges 2
  • The rules for type casting are different between == and <=/>=. – Pointy Commented Apr 28, 2016 at 22:21
  • 2 You can read this about greater-than and less-than, and this about ==. – Pointy Commented Apr 28, 2016 at 22:23
Add a comment  | 

1 Answer 1

Reset to default 24

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:

Return true if x and y refer to the same object. Otherwise, return false.

Each usage of {} creates a new object, so this check fails and the result is false.

=== 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: >= / <= coerce in a different way than == / ===.

发布评论

评论列表(0)

  1. 暂无评论