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

JS中的数组的sort方法使用示例_javascript技巧

WBOY
Release: 2016-05-16 17:03:00
Original
1119 people have browsed it
复制代码 代码如下:

var values=[0,1,5,10,15];
values.sort();
alert(values);// 输出0,1,10,15,5

这是因为sort会调用每一项的toString方法进行比较,"10"比"5"小,故在前面。
要实现对数值进行排序,则需要定义一个比较函数,并将该函数传入sort。
复制代码 代码如下:

function compare(value1,value2){
if(value1return -1;
}else if(value1>value2){
return 1;
}else{
return 0;
}
}
var values=[0,1,5,10,15];
values.sort(compare);
alert(values);// 输出0,1,5,10,15

这是正向,反向只需把比较函数中-1和1交换过来就ok了。
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!