Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

javascript - Why is an object greater/less than or equal to a different object?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 == / ===.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...