Home  >  Article  >  Web Front-end  >  How does the sortNumber function in js sort an array?

How does the sortNumber function in js sort an array?

不言
不言Original
2018-08-14 16:43:113973browse

What this article brings to you is about how the sortNumber function in js sorts arrays? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

There is a sort method in JS to implement sorting, but simply using the sort method is not enough. To implement numerical sorting, you also need to use a function called sortNumber.

For example: I use the sort method to demonstrate its shortcomings (only the key codes are listed):

var arr = new Array(99,66,888,694898,116,46,41);
document.write("排序前:" +arr);
document.write("<br/>")
document.write("排序后:" +arr.sort());

Result:

Use sortNumber method (only key codes are listed):

 function sortNumber(a,b)
    {
        return a - b;
    }
    var arr = new Array(99,66,888,694898,116,46,41);
    document.write("排序前:" +arr);
    document.write("<br/>")
    document.write("排序后:" +arr.sort(sortNumber));

Result:

Explanation reason:

sort sorting method:
It doesn't sort the numbers by numerical magnitude.
sortNumber sorting function:
If no parameters are used when calling this method, the elements in the array will be sorted in alphabetical order. To be more precise, they will be sorted in the order of character encoding.
To achieve this, you should first convert the elements of the array into strings (if necessary) for comparison.
If you want to sort by other criteria, you need to provide a comparison function, which compares two values ​​and returns a number that describes the relative order of the two values.
The comparison function should have two parameters a and b, and its return value is as follows:
If a is less than b, a should appear before b in the sorted array, then a value less than 0 is returned.
If a is equal to b, return 0.
If a is greater than b, return a value greater than 0.

Related recommendations:

js encapsulates the _new function and how to implement the new keyword (with code test)

js basic syntax Introduction: data types and variable types

Summary of the usage of common regular expressions in js

The above is the detailed content of How does the sortNumber function in js sort an array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn