根据对象属性的属性值,对对象进行排序

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    var data = [{
        userName:"aaa",
        age:18
    },{
        userName:"ccc",
        age:24
    },{
        userName:"bbb",
        age:12
    }];
    var userNameSort = data.sort(compairsonFn("userName"));
    console.log("============按姓名排序============");
    console.log(userNameSort);
    //var ageSort = data.sort(compairsonFn("age"));
    //console.log("=============按年龄排序============");
    //console.log(ageSort);
});
function compairsonFn(porpertyName){
    return function(obj1,obj2){
        var value1 = obj1[porpertyName];
        var value2 = obj2[porpertyName];
        if(value1<value2){
            return -1;
        } else if (value1>value2){
            return 1;
        } else{
            return 0;
        }
    };
}
</script>
</body>
</html>

 

posted on 2017-05-17 17:04  jasonduanmu  阅读(359)  评论(0编辑  收藏  举报

导航