Sort (): Arranges array items in ascending order, sort invokes the ToString () method of each array item, and then compares the string, determined how to sort, even if each item in the array is a numeric value, the string is compared;
Reverse (): Reverses the order of the array items;
Cases:
var values = [0,1,2,10,15,23,36];
Values.sort ();
Console.log (values);
Values.reverse ();
Console.log (values);
---output: (7) [0, 1, 10, 15, 2, 23, 36]
(7) [36, 23, 2, 15, 10, 1, 0]
Such a sort is not the best scenario in many cases, so the sort () method can accept a comparison function as an argument so that it is possible to specify which value is in front of which value.
A comparison function can accept two parameters, as follows:
function Compare (value1,value2) {
if (value1 < value2) return-1;
else if (value1 > value2) return 1;
else return 0;
}
var values = [0,1,5,10,15,23];
Values.sort (Compare);
Console.log (values);
---output: (6) [0, 1, 5, 10, 15, 23]
You can also do this in descending order, as long as the value returned by the interchange comparison function can be
function Compare (value1,value2) {ifreturn 1; Else if return -1; Else return 0;} var values = [0,1,5,10,15,23];values.sort (Compare); Console.log (values);
---output: (6) [23, 15, 10, 5, 1, 0]
Reorder methods Sort, reverse