preface
Today is a sunny day, is looking for new material, see awesome group friends put forward a question is
why'1' < '10' == true
而 '2' < '10' == false
?
imagine
‘1’ < ’10’ == true But it makes sense here! Please listen to me slowly
First declare a point if other types of the same type really do not cast to compare.
However, if a String is of the same type, it will be converted to Unicode code alignment.
And the default conversion is the first character of Unicode code, if equal will be compared one by one, until the result is produced, will stop the comparison and return the result
Converting to code is:
'1'.charCodeAt() < '1'.charCodeAt() // Compare string 1 to Unicode code with string 1 to Unicode code
' ' < '0'.charCodeAt()
Copy the code
They compare the first ☝️ and get the same Unicode code, and then compare the second but ‘1’ has only one digit, so they get the Unicode code for ” and ‘0
That’s it, by the rule that null characters and numbers are strongly converted to numbers
Empty objects are converted to 0
So you get the result'1'< '10' == true
Set up!
The transformation rules are detailed:
‘0’ < “special contrast
In fact, there are special judgments like'0' < '
That’s because the null character passes throughUnicode code
isNaN
而'0'
Is 48Unicode code
NaN
It’s not legally specialNumber
Value and greater than the legal array, exceptInfinity
infinity
conclusion
Understanding this concept is a good way to explain why ‘1’ < ’10’ is that they are not different types of comparison, and not == comparison, size comparison will convert their first character to Unicode code size, if the first character comparison is the same unicode code will be compared one by one.
Extend the example
- The first one is because there’s a
number
So it’s converted tonumber
To compare - The second one is both
string
And the size is converted to the first letter of the contrastUnicode code
Contrast. After equivalent to' '
和Unicode code
The contrast of
Here’s another fun one
This is because the Unicode code for ‘select’ is larger than the Unicode code for ‘nu’
It also proves that every choice you make matters. Work together and make progress together. I’m Ah Jiang!