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(value1
return -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了。
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