This article mainly introduces the use of arrays sort and reverse in Javascript. The example analyzes the precautions and related skills for using sort and reverse, which has good reference value, for more information about how to use the array sort and reverse in Javascript, see the following example. Share it with you for your reference. The specific analysis is as follows:
The sort () method is used to sort the elements of an array.
Reverse () sorts the elements in the array in reverse order.
First, let's try the following code:
The Code is as follows:
Var values = [1, 0, 5, 15, 10];
Values. reverse ();
Console. log (values );
What is the output result:
[10, 15, 5, 0, 1]
Reverse () is simply to reverse the array, so what we want to talk about next is sort ()
The Code is as follows:
Var values = [1, 0, 5, 15, 10];
Values. sort ();
Console. log (values );
The output result of this function is:
[0, 1, 10, 15, 5]
What's going on?
In fact, the sort () function uses toString () transformation, while the String comparison uses ASCII. Therefore, it is better to write a sort () by ourselves if we need to sort the data.
The Code is as follows:
Var values = [1, 0, 5, 15, 10];
Function compare (value1, value2 ){
If (value1 <value2 ){
Return-1;
} Else if (value1> value2 ){
Return 1;
} Else {
Return 0;
}
}
Values. sort (compare );
Console. log (values );
If you replace-1 and 1, you can reverse sort them.
Current output result:
[0, 1, 5, 10, 15]
A simpler way is to use return value2-value1 in compare;
I hope this article will help you design javascript programs.