jQuery对JSON数组的简单排序

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="jquery-3.3.1.min.js"></script>
</head>
<body>
    <!-- 未经排序的 -->
    <table class = 'grid-table' id="tablea" border="1">
        <tr>
            <th>员工工号</th>
            <th>员工姓名</th>
            <th>员工年龄</th>
        </tr>
    </table>
    <!-- 按员工工号排序 -->
    <table class = 'grid-table' id="tableb" border="1">
        <tr>
            <th>员工工号</th>
            <th>员工姓名</th>
            <th>员工年龄</th>
        </tr>
    </table>
    <!-- 按员工年龄排序 -->
    <table class = 'grid-table' id="tablec" border="1">
        <tr>
            <th>员工工号</th>
            <th>员工姓名</th>
            <th>员工年龄</th>
        </tr>
    </table>


</body>
<script>
    $(function(){
        var people = [
            {
                'card_id':'0001',
                'name':'p1',
                'age':'25'
            },
            {
                'card_id':'0022',
                'name':'p2',
                'age':'22'
            },
            {
                'card_id':'0004',
                'name':'p3',
                'age':'66'
            }
        ];

        //$.each()是对数组,json和dom结构等的遍历,语法为$.each(arr,func)
        //而原生JS中则是[].forEach(function(value,index,array){
     //code something
        //   });
        //arr.forEach(function(value,index,array){
    // array[index] == value;    //结果为true
    // sum+=value;  
    // });
        $.each(people,function(index,value){
            $("#tablea").append('<tr><td>' + value.card_id + 
                '</td><td>' + value.name +
                '</td><td>' + value.age + '</td></tr>');
        });

        var card_id_people = people.sort(function(a,b){
            if(a.card_id < b.card_id){
                return -1;
            }else if(a.card_id > b.card_id){
                return 1;
            }else{
                return 0;
            };
        });
        console.log(card_id_people);
        $.each(card_id_people,function(index,value){
            $("#tableb").append('<tr><td>' + value.card_id + 
                '</td><td>' + value.name +
                '</td><td>' + value.age + '</td></tr>');
        });

        var age_people = people.sort(function(a,b){
            if(a.age < b.age){
                return -1;
            }else if(a.age > b.age){
                return 1;
            }else{
                return 0;
            };
        });
        console.log(age_people);
        $.each(card_id_people,function(index,value){
            $("#tablec").append('<tr><td>' + value.card_id + 
                '</td><td>' + value.name +
                '</td><td>' + value.age + '</td></tr>');
        });
    })
</script>
</html>

 

posted @ 2019-05-23 08:23  林不渡  阅读(1356)  评论(0编辑  收藏  举报