Understanding Lexicographical String Comparison: Why "11" is Less Than "3"?
In JavaScript, strings are compared lexicographically, meaning character by character, until a mismatch is found or one string ends. This behavior can lead to unexpected results when comparing strings that represent numbers.
Lexicographical Comparison in Action
Consider the following code:
<code class="javascript">if ('11' < '3') alert('true');</code>
This code evaluates to true because the first character of '11' ('1') is lexicographically less than the first character of '3' ('3'). In other words, JavaScript compares strings as character sequences, not as numbers.
Character Code Equivalence
The lexicographical ordering of characters is based on their Unicode character codes. The Unicode character code for '1' is 49, while the code for '3' is 51. Since 49 is less than 51, '1' comes before '3' in the character sequence.
Example Scenarios
Explicit Numeric Conversion
To compare strings as numbers, they can be explicitly converted using the operator:
<code class="javascript">+'11' < '3': False</code>
The above is the detailed content of Why is JavaScript\'s Lexicographical String Comparison Causing \'11\' to Be Less Than \'3\'?. For more information, please follow other related articles on the PHP Chinese website!