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

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

小云云
Release: 2017-12-25 14:46:08
Original
1472 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template