In javascript, the Array. sort () method is used to sort Array items in ascending order by default. The instance code is as follows:
Copy codeThe Code is as follows:
Var arrA = [6, 2, 4, 3, 5, 1];
ArrA. sort ();
Document. writeln (arrA );
// The result is: 1, 2, 3, 4, 5, 6.
The sort () method can accept a method as a parameter. This method has two parameters. Represent the two array items for each sort comparison.
This parameter is executed every time two array items are compared during sort () sorting, and two compared array items are passed as parameters to this function. When the return value of the function is 1, the order of two array items is exchanged. Otherwise, the order is not exchanged.
Example:
Copy codeThe Code is as follows:
Var arrA = [6, 2, 4, 3, 5, 1];
/** // * ArrA. sort ();
Document. writeln (arrA );
*/
Function desc (x, y)
...{
If (x> y)
Return-1;
If (x <y)
Return 1;
}
Function asc (x, y)
...{
If (x> y)
Return 1;
If (x <y)
Return-1;
}
ArrA. sort (desc); // sort by desc
Document. writeln (arrA );
Document. writeln ("<br> ");
ArrA. sort (asc); // sort by asc
Document. writeln (arrA );
// Output result:
6, 5, 4, 3, 2, 1
1, 2, 3, 4, 5, 6
In addition, an unnamed function can be directly put into the call of the sort () method. In the following example, the odd number is placed at the top and the even number is placed at the bottom. The example is as follows:
Copy codeThe Code is as follows:
Var arrA = [6, 2, 4, 3, 5, 1];
ArrA. sort (function (x, y )...{
If (x % 2 = 0)
Return 11;
If (x % 2! = 0)
Return-1;
}
);
Document. writeln (arrA );
// Output: 1, 5, 3, 4, 6, 2