First, let's talk about the reverse method.
The reverse method reverses the element positions in an Array object. During execution, this method does not create a new Array object.
For example:
Copy codeThe Code is 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. If the array contains other types, the array is reversed and the array is returned.
Sort Method
Returns an Array object whose elements have been sorted.
Copy codeThe Code is as follows:
Arrayobj. sort (sortfunction)
Parameters
ArrayObj
Required. Any Array object.
SortFunction
Optional. Is the name of the function used to determine the order of elements. If this parameter is omitted, the elements are listed in ascending order of ASCII characters.
The sort method sorts Array objects appropriately. During execution, no new Array objects are created.
If a function is provided for the sortfunction parameter, the function must return one of the following values:
Negative value if the first parameter is smaller than the second parameter.
Zero. If the two parameters are equal.
If the first parameter is greater than the second parameter.
Example 1 :()
Copy codeThe Code is as follows:
Var a, l; // declare the variable.
A = ["X", "y", "d", "Z", "v", "m", "r", false, 0];
L = a. sort (); // sort the array.
Alert (l); // returns the sorted array.
In this example, if the comparison function is not input, the elements are sorted in ascending order according to the ASCII character order. In addition, this array contains multiple types of data, even if the comparison function is input, it is still in ascending order of ASCII characters.
For example
Copy codeThe Code is as follows:
Var a, l; // declare the variable.
A = ["X", "y", "d", "Z", "v", "m", "r", false, 0];
L = a. sort (); // sort the array.
Alert (l); // returns the sorted array.
Ll = a. sort (compack );
Alert (ll); // returns the same result as above
Function compack (a, B ){
Return a-B;
}
When you need to sort numbers, you can use the sort method. You only need to input a comparison function to sort numbers in ascending or descending order.
Ascending Order:
Copy codeThe Code is as follows:
Var a, l; // declare the variable.
A = [6, 8, 9, 5.6, 90];
L = a. sort (compack); // sort the array.
Alert (l); // returns the sorted array.
Function compack (a, B ){
Return a-B;
}
Descending order:
Copy codeThe Code is as follows:
Var a, l; // declare the variable.
A = [6, 8, 9, 5.6, 90];
L = a. sort (compack); // sort the array.
Alert (l); // returns the sorted array.
Function compack (a, B ){
Return B-;
}
In the comparison function, a-B is returned in ascending order, and B-a is returned in descending order.