First let's talk about the reverse method first.
The reverse method reverses the position of an element in an Array object. During execution, this method does not create a new Array object.
For example:
Copy Code code as follows:
var array1 = [' A ', ' cc ', ' BB ', ' Hello ', false,0,3];
var array2 = [3,5,2,1,7,9,10,13];
Array1.reverse ();
Array2.reverse ();
alert (array1);
alert (array2);
If the array contains only numbers, the numbers are sorted in descending order, and if other types are included in the array, the array is inverted and the array is returned.
Sort method
Returns an Array object in which an element has been sorted.
Copy Code code as follows:
Arrayobj.sort (sortfunction)
Parameters
Arrayobj
Required option. Any Array object.
Sortfunction
Options available. is the name of the function used to determine the order of elements. If this argument is omitted, then the elements are sorted in ascending order in ASCII characters.
The sort method sorts the array object appropriately, and does not create a new array object during execution.
If you provide a function for the sortfunction parameter, the function must return one of the following values:
Negative value if the first argument passed is smaller than the second argument.
0 if two parameters are equal.
Positive value if the first argument is larger than the second argument.
Example 1: ()
Copy Code code as follows:
var a, l; Declare a variable.
A = ["X", "Y", "D", "Z", "V", "M", "R", false,0];
L = A.sort (); The sort array.
Alert (l); Returns the sorted array.
In this example there is no incoming comparison function so the elements are sorted in ascending order of ASCII character, and the array contains multiple types of data, so even if the comparison function is passed in, it is still ascending in the ASCII character order.
For example
Copy Code code as follows:
var a, l; Declare a variable.
A = ["X", "Y", "D", "Z", "V", "M", "R", false,0];
L = A.sort (); The sort array.
Alert (l); Returns the sorted array.
ll = A.sort (compack);
Alert (ll);//return to the same as above
function Compack (a,b) {
return a-b;
}
We can use the sort method when we need to sort the numbers, just passing in a comparison function makes it easy to get to the ascending and descending order.
Ascending:
Copy Code code as follows:
var a, l; Declare a variable.
A = [6,8,9,5.6,12,17,90];
L = A.sort (compack); The sort array.
Alert (l); Returns the sorted array.
function Compack (a,b) {
return a-b;
}
Descending:
Copy Code code as follows:
var a, l; Declare a variable.
A = [6,8,9,5.6,12,17,90];
L = A.sort (compack); The sort array.
Alert (l); Returns the sorted array.
function Compack (a,b) {
return b-a;
}
Returns A-b in ascending order in the comparison function, descending back to b-a.