根據對象的某個屬性名的值重新排序

var list=[
    {
        name:"aaa",
        score:80
    },
    {
        name:"bbb",
        score:70
    },
    {
        name:"ccc",
        score:90
    },
    {
        name:"ddd",
        score:60
    }
];
function compareFn(propertyName){
    return function(obj1,obj2){
        var value1 = obj1[propertyName];
        var value2 = obj2[propertyName];
        if(value1 < value2){
            //return 1 //max-min
            return -1 //min-max
        }else if(value1 > value2){
            //return -1;//max-min
            return 1;// min-max
        }else{
            return 0;
        }
    }
}
list.sort(compareFn('score'));//-1,從min-max排序,1 從max-min

 

相關文章
相關標籤/搜索