Such as:
var a=[1,5,3,7];
A.sort (function (A, b) {return b-a});//from large to small arrangement
So if the order of the complex points should be how to write the comparison function.
For comparison function f (a,b) {...}, if a positive number is returned, A and b need to be exchanged or not exchanged. So we can all write the comparison function according to the following format:
Copy Code code as follows:
function f (A, B) {
if (...) {
return 1;
}
return-1;
}
Then all we have to do is write the conditions inside the if, which is to return a and B conditions that need to be exchanged. For example: for Var a=["A", "a", "B", "B", to be case-insensitive and sorted from large to small, only when a.tostring (). toLowerCase () < B.tostring (). toLowerCase (), swap A, B, So fill the IF condition with this. The comparison function is:
function f (A, B) {
if (a.tostring (). toLowerCase () < B.tostring (). toLowerCase ()) {
return 1;
}
return-1;
}
Another example: to make the elements of an array in the order of odd-numbered, even, if you want a, b exchange, only if a is an even number and B is odd, and then sorted from small to large, only if a, B are odd or even and a>b. As follows:
<script type= "Text/javascript" > var a = [1, 7, 3, 9, 5, 6, 2, 8, 4]; function f (A, B) {if (0 = a% 2 && 1 = b% 2) {return 1; } if ((1 = a% 2 && 1 = b% 2 | | 0 = a% 2 && 0 = b% 2) && a > B) {return 1; } return-1; Alert (A.sort (f)); </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
Author: jaychow