Why is it true when > =, < = when comparing two objects?
a = {a:1};
b = {b:1};
console.log("a == b : ", a==b); // a == b : false
console.log("a > b : ", a>b); // a > b : false
console.log("a < b : ", a<b); // a < b : false
console.log("a >= b : ", a>=b); // a >= b : true
console.log("a <= b : ", a<=b); // a <= b : true
First of all, a book “Javascript you don’t know” is highly recommended.
The book talks about this problem:Step github
That is to say, first of all:
- If the two values compared by’ <‘ or’ >’ are string, a simple dictionary order (natural alphabetical order) comparison is performed on the characters
- If the two values compared by’ <‘ or’ >’ are both number, they are directly compared
- If not 1, 2. The ToPrimitive cast is first called on the two values. If one of the return values of the two calls is not string, then the Tonumber operation rule is used to cast the two values into Number values and compare the numbers.
So:
a = {a:1}; // ToPrimitive => "[object Object]" b = {b:1}; // ToPrimitive => "[object Object]" A > b // false, in dictionary order [object Object] is not greater than [object Object] A < b // false, in dictionary order [object Object] is not less than [object Object] A == b // false, the object "= = =" compares whether the references held are the same A <= b // true, the language specification says that for a < = b, it actually evaluates b < a first and then inverts that junction Fruit. Because b < a is also false, the result of a <= b is true.