Comparing numbers of type string

前端 未结 1 680
轻奢々
轻奢々 2021-01-26 09:29

I\'m implementing a sort function and came across the following:

\'49\' > \'5\' // false
\'49\' > \'4\' // true

new String(49).localeCompare(\'4\') // 1
n         


        
相关标签:
1条回答
  • 2021-01-26 10:12

    That is actually expected behavior when comparing strings, as described here. The easiest thing for this situation would be to convert the values to numbers for comparison if you want to compare them as numbers.

    Thinking outside the box a little, you could first compare the length of the strings before using the > operator. If they are numeric strings, the longer string would have a higher value (assuming you don't have numbers like '0024'). If they are equal in length, the > operator would then work as you expect.

    0 讨论(0)
提交回复
热议问题