Home >Web Front-end >JS Tutorial >js 数组array sort排序实例

js 数组array sort排序实例

WBOY
WBOYOriginal
2016-06-01 09:54:591628browse

语法:

arrayObject.sort(sortby)


参数描述:

参数 描述
sortby 可选。规定排序顺序。必须是函数。


实例一:对数组元素按照大小排序:

<code><script type="text/javascript">
var arr=[12,1,45,7,44,23];
function sortfunc(a,b){
    return a-b;
}
alert(arr.sort(sortfunc));
</script></code>

实例二:
按照对象属性排序,这里可以写一个通用的sort排序函数。此处将函数作为返回值,然后将返回的函数作为sort的参数。这样可以不用为每一个排序规则写一个函数。代码如下:

<code><script type="text/javascript">
function person(name,age,weight,height){
    this.name=name;
    this.age=age;
    this.weight=weight;
    this.height=height;
}
var person1=new person("zhangsan",33,60,170);
var person2=new person("lisi",22,65,175);
var person3=new person("wanger",37,54,179);
var person4=new person("job",15,50,188);
var person5=new person("hikk",24,67,165);
var person6=new person("milo",28,80,172);
var arr=[person1,person2,person3,person4,person5,person6];
function sortbyatt(field){
    var sortfun=function(obj1,obj2){
        if(obj1[field]>obj2[field])return 1;
        else if(obj1[field]==obj2[field])return 0;
        else return -1;
    }
    return sortfun;
}
//arr.sort(sortbyatt("name"));  //按name排序;
//arr.sort(sortbyatt("age"));   //按age排序;
arr.sort(sortbyatt("weight"));  //按weight排序;
//arr.sort(sortbyatt("height")); //按height排序;
for(var i=0;i<arr.length;i++){
    document.write(arr[i].name+"----",arr[i].age+"----",arr[i].weight+"----",arr[i].height+"<br/>");
}
</script></code>

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