1. There are two methods that can be used to reorder directly in the array: reverse () and sort ().
The return value of the reverse () and sort () methods is the sorted array. The reverse () method reverses the order of the array items:
var values=[1,2,3,4,5];
Values.reverse ();
alert (values); 5,4,3,2,1
By default, the sort () method arranges an array in ascending order, and the sort () method invokes the ToString () transformation method for each array item, and then compares the string to determine how to sort. Even if each item in the array is a numeric value, the sort () method compares the string:
var values = [0,1,5,10,15];
Values.sort ();
alert (values); 0,1,10,15,5
Therefore, the sort () method can receive a comparison function as an argument.
function Compare (value1,value2) {
if (value1 < value2) {
return-1;
} else if (value1 > value2) {return
1;
} else{return
0;
}
This comparison function can be applied to most data types, as long as it is passed as a parameter to the sort () method:
var values = [0,1,3,7,9,15];
Values.sort (compare);
alert (values); 0,1,3,7,9,15
You can also create a descending sort by comparing functions by exchanging function return values:
function Compare (value1, value2) {
if (value1<value2) {return
1;
} else if {
return-1;
} else{return
0;
}
The sorting criteria for the sort () function are:
The parameter is greater than the adjacent two element exchange position of 0,arr;
The adjacent two elements with a parameter less than 0,arr do not exchange positions;
The parameter equals 0,arr two elements equal in size, so the Compare custom function must return a numeric value.
2. For numeric types or valueof () methods, the object type of the numeric type is returned.
You can use a simpler comparison function. This function can be as long as the second value is minus the first value.
function Compare (value1,value2) {return
value2-value1;
}
The above is a small set of JS to introduce the array reordering method, I hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!