admin管理员组

文章数量:1399986

If I were to run "[6,3,8,7,5,2,1,9,4,0].sort()" I get "[0,1,2,3,4,5,6,7,8,9]" as an output like you would expect. It sorts the numbers from smallest to largest. But if I were to run "[2,3,1,4e-20].sort()" I get "[1,2,3,4e-20]" as an output. Why does the ".sort()" function treat "4e-20" as larger than "3"? Even if you run "3>4e-20" you get "true" as an output, showing that JavaScript does realize that "4e-20" is an incredibly tiny number. But the sort function treats it as an incredibly larger number. Why is this? and is there some way I can change it, or do I just have to write my own function?

If I were to run "[6,3,8,7,5,2,1,9,4,0].sort()" I get "[0,1,2,3,4,5,6,7,8,9]" as an output like you would expect. It sorts the numbers from smallest to largest. But if I were to run "[2,3,1,4e-20].sort()" I get "[1,2,3,4e-20]" as an output. Why does the ".sort()" function treat "4e-20" as larger than "3"? Even if you run "3>4e-20" you get "true" as an output, showing that JavaScript does realize that "4e-20" is an incredibly tiny number. But the sort function treats it as an incredibly larger number. Why is this? and is there some way I can change it, or do I just have to write my own function?

Share Improve this question edited Jun 21, 2014 at 19:15 user2864740 62.1k15 gold badges158 silver badges227 bronze badges asked Jun 21, 2014 at 19:05 user1432532user1432532 3491 gold badge5 silver badges14 bronze badges 3
  • Please read over this sentence carefully: "Even if you run "3>4e-20" you get "true" as an output, showing that JavaScript does realize that "4e-20" is an incredibly tiny number." – IMSoP Commented Jun 21, 2014 at 19:08
  • possible duplicate of arr.sort() does not sort integers correctly (this also applies to non-integer numbers) – user2864740 Commented Jun 21, 2014 at 19:13
  • stackoverflow./questions/7000851/… , stackoverflow./questions/1063007/… , stackoverflow./questions/11914665/… – user2864740 Commented Jun 21, 2014 at 19:14
Add a ment  | 

3 Answers 3

Reset to default 6

From MDN Array.sort:

"The default sort order is according to string Unicode code points."

It then goes on "[to] pare numbers instead of strings, the pare function can simply subtract b from a. The following function will sort the array ascending":

function pareNumbers(a, b) {
  return a - b;
}

You might want to do this:

[2, 3, 1, 4e-20].sort(function (a, b) {
    return a - b;
});

That happens because (according to MDN) when no sorter function is provided, it uses an unicode string parator.

Array.sort() in javascript does not sort by < and >, it instead does a lexical sort, which means it treats the numbers as strings and sorts them that way. This is what causes the longer 4e-20 to be sorted higher than the shorter and (lexically) lower 3.

While a - b works, this is a theoretically faster parison because it is branchless: (a > b) - (a < b)

本文标签: