Home >Web Front-end >JS Tutorial >How does the sortNumber function in js sort an array?
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.
var arr = new Array(99,66,888,694898,116,46,41); document.write("排序前:" +arr); document.write("<br/>") document.write("排序后:" +arr.sort());
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));
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!