Copy the code code as follows:
<html>
<head>
<title>sort() method of array</title>
<script>
/*
sort()
1. No copy is generated, the original array is directly referenced.
2. If no parameters are used when calling this method, the elements in the array will be sorted alphabetically.
To be more precise, it is sorted according to the order of character encoding.
To achieve this, the elements of the array should first be converted to strings (if necessary) for comparison.
3. If you want to sort according to other criteria, you need to provide a comparison function, which compares two values.
It then returns a number describing 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 equals b, then 0 is returned.
If a is greater than b, a value greater than 0 is returned.
*/
var arr = [2,4,8,1,22,3];
var arrSort= arr.sort();//Not sorted correctly, the array is converted to a string first and then sorted
document.write("The default sorted array is: " + arrSort);//1,2,22,3,4,8
document.write("<br/>");
//Comparison function
function mysort(a,b){
return ab;
}
var arrSort2 = arr.sort(mysort);//Pass in the comparison function
document.write("The array of comparison parameters passed in is: " + arrSort2);//Correct sorting
document.write("<br/>");
document.write("The original array is: " + arr);
</script>
</head>
<body>
<div id="time"></div>
</body>
</html>