Reordering method in JavaScript

Reordering method:

JavaScript built-in function reordering methods: reverse() and sort();

var array = [1,2,3,4]
array.reverse();
alert(array);//4,3,2,1

This method is not flexible enough (it is more convenient if you only want to reverse the array reverse). The
sort method is arranged in ascending order by default. The method can only operate on numbers within 10, with the smallest value at the front and the largest at the end, and toString() will be automatically called Transformation method, compare after getting string.

var array = [1,2,10, 15,9]
array.sort();
alert(array); //1,10,15,2,9

So the sort() method can receive a comparison function to determine which value needs to be in front of which value.
The comparison function receives two parameters. If the first parameter should be before the second parameter, it returns a negative number, if the two parameters are equal, it returns 0, and if the first parameter should be after the second parameter, it returns a positive number. .
Comparison function (ascending order):

function compare(value1,value2){
   If(value1 < value2){
     return -1
} else if( value1> value2){
     return 1  
} else {
     return 0 
}
}

var array = [1,2,10, 15,9]
array.sort(compare);
alert(array); //1,2,9,10,15

Comparison function (descending order):

function compare(value1,value2){
   If(value1 < value2){
     return 1
} else if( value1> value2){
     return -1  
} else {
     return 0 
}
}

Guess you like

Origin blog.csdn.net/Jonn1124/article/details/108809505