JavaScript - The internal JavaScript sort method sorts numeric data - True or False? [closed]
The internal JavaScript sort method sorts numeric data - True or False?
If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order. For example, "80" comes before "9" in lexicographic order, but in a numeric sort 9 comes before 80.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
So the answer is False.
It seems it doesn't sort very well...
[3,5,1,5,10,0,99,10,12].sort()
[0, 1, 10, 10, 12, 3, 5, 5, 99] // result
But you can easily make it sort ok:
[3,5,1,5,10,0,99,10,12].sort(function(a,b) {return parseInt(a) > parseInt(b)})
[0, 1, 3, 5, 5, 10, 10, 12, 99] // result
精彩评论