jquery list对象排序

2025-03-28 18:46:47
推荐回答(3个)
回答1:

使用SORT进行排序。

示例如下:


    

    sort()对数组排序,不开辟新的内存,对原有数组元素进行调换
    

    
    1、简单数组简单排序
    
        var arrSimple=new Array(1,8,7,6);
        arrSimple.sort();
        document.writeln(arrSimple.join());
    
    

    

    2、简单数组自定义排序
    
        var arrSimple2=new Array(1,8,7,6);
        arrSimple2.sort(function(a,b){
            return b-a});
        document.writeln(arrSimple2.join());
    
    解释:a,b表示数组中的任意两个元素,若return > 0 b前a后;reutrn < 0 a前b后;a=b时存在浏览器兼容
    简化一下:a-b输出从小到大排序,b-a输出从大到小排序。
    

    

    3、简单对象List自定义属性排序
    
        var objectList = new Array();
        function Persion(name,age){
            this.name=name;
            this.age=age;
            }
        objectList.push(new Persion('jack',20));
        objectList.push(new Persion('tony',25));
        objectList.push(new Persion('stone',26));
        objectList.push(new Persion('mandy',23));
        //按年龄从小到大排序
        objectList.sort(function(a,b){
            return a.age-b.age});
        for(var i=0;i            document.writeln('age:'+objectList[i].age+' name:'+objectList[i].name);
            }
    
    

    

    4、简单对象List对可编辑属性的排序
    
        var objectList2 = new Array();
        function WorkMate(name,age){
            this.name=name;
            var _age=age;
            this.age=function(){
                if(!arguments)
                {
                    _age=arguments[0];}
                else
                {
                    return _age;}
                }
                
            }
        objectList2.push(new WorkMate('jack',20));
        objectList2.push(new WorkMate('tony',25));
        objectList2.push(new WorkMate('stone',26));
        objectList2.push(new WorkMate('mandy',23));
        //按年龄从小到大排序
        objectList2.sort(function(a,b){
            return a.age()-b.age();
            });
        for(var i=0;i            document.writeln('age:'+objectList2[i].age()+' name:'+objectList2[i].name);
            }
    
    

回答2:

举个例子:

var arr=[
            {price:12},
            {price:5},
            {price:2},
            {price:512},
            {price:182}
        ];
        arr.sort(function(a,b){
            return a.price-b.price;
        });
        console.log(arr)

这样就可以了,arr是你的数据

回答3:

三十三、JQuery简介+选择器

相关问答