开发者社区> 问答> 正文

JavaScript中的sort如果对字符串/对象进行排序,排序规则是怎样的?

例如对

[{

                'pimg': 'images/award4.png',
                'pname': 'xxxx模型'

            }, {

                'pimg': 'images/award3.png',
                'pname': '休闲户外衣服'

            }, {

                'pimg': 'images/award3.png',
                'pname': '精致日版动漫挂扣'

            }, {

                'pimg': 'images/award2.png',
                'pname': '炫酷耳机'

            }
]

这样一个数组进行sort排序,具体是先用哪个跟哪个对比,如何判断先后?

展开
收起
a123456678 2016-03-13 11:38:45 4218 0
1 条回答
写回答
取消 提交回答
  • The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.
    arr.sort([compareFunction])
    compareFunction
    Optional. Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.
    sort方法如果不提供compareFunction比较函数,那么就把数组中的元素转成字符串后按字符的Unicode码点进行比较。元素按不同的类型转成字符串的结果是不同的,对于JSON格式对象来说,其转换的结果就是[object Object]。
    故问题中的数组sort后的结果是没有变化

    可以传入一个自定义的比较函数来进行你想要的排序结果

    var tempArray=[{
        'pimg': 'images/award4.png',
        'pname': 'xxxx模型'
    }, {
        'pimg': 'Zimages/award3.png',
        'pname': '休闲户外衣服'
    }, {
        'pimg': 'images/award3.png',
        'pname': '精致日版动漫挂扣'
    }, {
        'pimg': 'images/award2.png',
        'pname': '炫酷耳机'
    
    }
    ];
    tempArray.sort();
    console.log(tempArray);
    tempArray.sort(function(a,b){
        if(a["pimg"]===b["pimg"]){
            if(a["pname"]>b["pname"]){
                return 1;
            }else if(a["pname"]<b["pname"]){
                return -1;
            }else{
                return 0;
            }
        }else{
           if(a["pimg"]>b["pimg"]){
               return 1;
           }else{
               return -1;
           }
        }
    
    });
    console.log(tempArray);
    2019-07-17 19:02:21
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
JavaScript异步编程 立即下载
Delivering Javascript to World 立即下载
编程语言如何演化-以JS的private为例 立即下载