Sort Array ()
The sort () method causes the elements in the array to be arranged in a certain order.
Grammar:
Arrayobject.sort (method function)
Parameter description:
1. If the < method function is not specified, it is sorted in Unicode code order.
2. If you specify the < method function, then sort by the < method function > The sorting method specified.
Myarray.sort (SortMethod);
Note: The function 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:
A return value of <=-1 indicates that A appears before B in the sorted sequence. If the return value >-1 && <1, then A and B have the same sort order. A return value of >=1 indicates that A appears after B in the sorted sequence.
1. Use sort () to sort the array with the following code:
<script type= "Text/javascript" > var myarr1 = new Array ("Hello", "John", "Love", "JavaScript"); var myarr2 = new Array ("n", "+", "Max", "6", "+", "1"); document.write (Myarr1.sort () + "<br>"); document.write (Myarr2.sort ());</script>
Operation Result:
hello,javascript,john,love1,100,16,50,6,80
Note: The above code does not sort the numbers by the size of the numeric values.
2. To achieve this, you must use a sort function with the following code:
<script type= "Text/javascript" > function Sortnum (A, a) { return a-B;//ascending, such as descending, put "A-a" into "b-a"} var Myarr = new Array ("n", "+", "a", "6", "+", "1"); document.write (Myarr + "<br>"); document.write (Myarr.sort (sortnum));</script>
Operation Result:
80,16,50,6,100,11,6,16,50,80,100
Sorting array sort ()