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

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

例如对

[{

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

            }, {

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

            }, {

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

            }, {

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

            }
]

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


你可以自己写个比较函数,按照自己的想法去进行排序。比较函数要求返回-1,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);

自定义一个函数比较,相等返回0,小于返回负数 大于返回正数

var a = [ { v:12},{v:11},{v:13} ];

function fn(x,y)
{
    return x.v - y.v;
}
console.log(a.sort(fn)) 

七天母公司 铂涛集团 体验消费极客挑战大赛 欢迎参与 详情请点击 http://t.cn/Rq01p7C


按照字符编码的顺序

【热门文章】
【热门文章】