Home > Web Front-end > JS Tutorial > body text

How the function sort() works in javascript

一个新手
Release: 2017-09-09 09:05:40
Original
1491 people have browsed it

var arr = [2,34,242,12,3,2,23,3];// 定义一个数组
Copy after login
arr.sort(function (a,b) {
// a -->代表每一次执行匿名函时候,找到的数组中的当前项;
// b -->代表当前项的后一项;
Copy after login
return a - b; // 升序时: 如果a>b,那么返回的值>0,a和b交换位置;
return b - a; // 降序时: 如果b>a,那么返回的值>0,a和b交换位置;
//-> 原理:return的值可能是一个大于0的数也或者可能是小于等于0的数,如果return后的值大于0则让数组a和b交换一下位置;小于等于0,则原来数组中的位置不变;
Copy after login
return 1; // 表示不管a和b谁大,每一次都返回一个恒大于0的数,也就是说每一次a和b都要交换位置,最后的结果就是原有数组倒过来排列了,相当于数组的reverse()方法;
Copy after login

})

The above is the detailed content of How the function sort() works in javascript. 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