Use the sort () method to sort the arrays numerically.
function Sortnumber (A, b) { return a- b} var arr = new Array (6) arr[ 0] = "Ten" arr[ 1] = "5" arr[ 2] = "
arr[ 3] = "
arr[ 4] =" $ "
arr[ 5] = "1"
document.write (arr + "<br/>"
) document.write (Arr.sort (sortnumber)) </script></body>
Arr.sort (Sortnumber)
Arr.sort (): A system function that handles an array of arr two adjacent elements.
Here Sortnumber is a custom sort condition.
Because the sort () function is sorted by an adjacent two-element exchange position with a parameter greater than 0,arr;
The adjacent two elements with a parameter less than 0,arr do not exchange positions;
A parameter equal to 0,arr is equal to the size of the adjacent two elements, so the Sortnumber custom function must return a numeric value.
(A-B) indicates that the next two elements are subtracted from the latter element by the previous element. and return this value, the sort () function determines whether the current two elements of Arr are swapped for positions based on the positive or negative value of the number.
Conversely: B-a turned into reverse. This means that the b-a represents the next two elements minus the previous element. and returns the value, the sort () function determines whether the current two elements of Arr are swapped for positions based on the positive or negative value of the number.
JavaScript sort () method description
If the method is called without parameters, the elements in the array are sorted alphabetically, more precisely, by the order in which the characters are encoded. To do this, you should first convert the elements of the array to a string, if necessary, for comparison.
If you want to sort by other criteria, you need to provide a comparison function that 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 with the following return values:
- If a is less than B, a value that is less than 0 is returned if a should appear before B in the sorted array.
- If a equals B, 0 is returned.
- If a is greater than B, a value greater than 0 is returned.
JavaScript uses the sort () method to sort the array numerically