Home  >  Article  >  Web Front-end  >  Detailed example of JavaScript array sorting reverse() and sort() methods

Detailed example of JavaScript array sorting reverse() and sort() methods

小云云
小云云Original
2017-12-25 14:46:081430browse

This article mainly introduces the JavaScript array sorting reverse() and sort() methods in detail. Friends in need can refer to it. I hope it can help everyone.

There are two methods for sorting arrays in JavaScript: reverse() and sort().

The reverse() method will reverse the order of the array items:


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

The sort() method will sort the array items in ascending order of the string, sort() The method calls the tostring() method of each array item. Even if each item in the array is a numeric value, the sort() method compares strings:


 var arr = [1,2,11,15,5];
arr.sort();
alert(arr); // 1,11,15,2,5

This approach is not the best solution in many cases, so the sort() method can receive a comparison function as a parameter. The comparison function takes two parameters. If the first parameter should be before the second parameter, it needs to return a negative number. If the two parameters are equal, it will return 0. If the first parameter should be after the second parameter, it will return a Positive numbers:


var arr = [1,2,11,15,5];
arr.sort(function(val1,val2){
return val1-val2;
 });
 alert(arr); // 1,2,5,11,15

Because comparison functions affect the sorting results by returning a value less than zero, equal to zero, or greater than zero, the subtraction operation can handle these situations well.

Related recommendations:

JavaScript reverse() method to reverse the order of elements in an array

About php array_reverse() function Recommended 10 articles

Javascript array sort() method and reverse() method_javascript skills

The above is the detailed content of Detailed example of JavaScript array sorting reverse() and sort() methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn