问题
How should I understand these?
null>0
> false
null==0
> false
null>=0
> true
回答1:
The relational operators (>= and <=), perform type coercion (ToPrimitive), with a hint type of Number, all the relational operators present have this behavior.
You can see the inner details of this process in the The Abstract Relational Comparison Algorithm.
On the other hand, the Equals operator (==), if an operand is null it only returns true if the other is either null or undefined, no numeric type coercion is made.
null == undefined; // true
null == null; // true
Check the inner details of this process in the The Abstract Relational Comparison Algorithm.
Recommended articles:
- typeof, == and ===
- Notes on ECMAScript Equality Operators
回答2:
The relative comparison operators imply a numeric context, so in those cases (>, >=) the null is converted to a number (zero).
In the == case, however, both values are treated as boolean values, and Javascript doesn't think that null should be equal to any other "falsy" values. It's kind-of weird. The equality algorithm for == has a bunch of special cases, and null is one of those. It's only == to itself and undefined.
回答3:
When null is used in a numeric experession it evalutes to 0, that explains your > and >= cases.
== is more subtle. Informally, null is not the same as zero, so it kind of makes sense.
回答4:
Interesting! It seems like Javascript needs a couple new identity operators like >== and <==. Although I am not sure that would make much sense, given the numerical implications of > and <.
This gives the expected result...
(null > 0 || null === 0);
来源:https://stackoverflow.com/questions/3372346/javascript-comparison-question-null-0