Home  >  Article  >  Web Front-end  >  javascript function

javascript function

高洛峰
高洛峰Original
2016-11-04 16:41:28981browse

array.sort(function(a, b){ return a -b ; } ) Sort the array array from small to large.

[11, 22, 586, 10, -58, 86].sort(function(a, b){ return a -b; } ) Return: [-58, 10, 11, 22, 86, 586]

The principle of sorting is to compare every two numbers, and then change the position of the elements in the array according to the positive or negative.
For example, in the first comparison, a is 11, b is 22, and then 11-22 is returned. The negative position remains unchanged.

array.sort(function(a, b){ return b - a ; } ) Sort the array in descending order.

[11, 22, 586, 10, -58, 86].sort(function(a, b){ return b - a ; } ) Returns: [586, 86, 22, 11, 10, -58]


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