问题
When we use The Less-than-or-equal Operator this is work under the hood with The Abstract Relational Comparison Algorithm. For example.
a <= b;
Convert to JavaScript like this
!(b < a)
And EcmaScript Spesification says (http://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5) which indicates that at least one operand is NaN less than return undefined And this is meaning
var a = 1;
var b = "asd"
a < b // b.toNumber() => NaN and this is operation return undefined (false)
If we use like this
var a = 1;
var b = "asd"
a <= b // this convert to !(b < a) and (b<a) return undefined
// and !(undefined) must be true
But EcmaScript spesification says this is return false. This is interesting for me what is reason this?
回答1:
While <= does use the Abstract Relational Comparison Algorithm, a <= b
isn't equivalent to !(b < a)
. It is equivalent to b < a !== false ? false : true
(where <
represents the Abstract Relational Comparison Algorithm, not the JavaScript <
operator which can never evaluate to undefined
), which behaves the same as !(b < a)
when b < a
is truthy or exactly false
, but does not behave the same when b < a
is falsey in general. If b < a
evaluates to undefined
, the whole expression will evaluate to false
.
This is defined in the spec at step 6 here: https://www.ecma-international.org/ecma-262/5.1/#sec-11.8.3
- Let r be the result of performing abstract relational comparison rval < lval with LeftFirst equal to false.
- If r is true or undefined, return false. Otherwise, return true.
The Abstract Relational Comparison Algorithm can only evaluate to true
, false
, or undefined
; so the "Otherwise" in step 6 can only apply when r
is false
, making a <= b
equivalent to b < a !== false ? false : true
(again, where <
represents the Abstract Relational Comparison Algorithm).
来源:https://stackoverflow.com/questions/57260084/the-less-than-or-equal-operator-with-nan