< ;title>sort() method of array
<script> <br>/* <br>sort() <br>1. No copy is generated, the original array is directly referenced<br>2. If no parameters are used when calling this method, the elements in the array will be sorted in alphabetical order. <br>To be more precise, they will be sorted in the order of character encoding. <br>To achieve this, first convert the elements of the array into strings (if necessary) for comparison. <br><br>3. If you want to sort according to other criteria, you need to provide a comparison function, which compares two values, <br> and then returns a number that describes the relative order of the two values. <br>The comparison function should have two parameters a and b, and its return value is as follows: <br>If a is less than b, a should appear before b in the sorted array, then return a value less than 0. <br>If a is equal to b, return 0. <br>If a is greater than b, return a value greater than 0. <br><br>*/ <br><br>var arr = [2,4,8,1,22,3]; <br>var arrSort= arr.sort();//The array is not sorted correctly Convert to string first, then sort <br>document.write("The default sort array is: " arrSort);//1,2,22,3,4,8 <br>document.write("< br/>"); <br><br>//Comparison function <br>function mysort(a,b){ <br>return a-b; <br>} <br><br>var arrSort2 = arr.sort (mysort);//Pass in the comparison function<br>document.write("The array of comparison parameters passed in is: " arrSort2);//Correct sorting<br>document.write("<br/>") ; <br><br>document.write("The original array is: " arr); <br><br></script>
< body>