继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

调用js内嵌函数sort对json数据排序

resharpe
关注TA
已关注
手记 102
粉丝 7244
获赞 3476

完整的html代码如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="div"></div>
</body>
<script>
    var jsonData={
        "id": "e00101",
        "name": "计量箱(柜)",
        "deal": {
            "keyname": "处理",
            "type": "radio",
            "values": [
                {
                    "key": "create",
                    "value": "新建"
                },
                {
                    "key": "refresh",
                    "value": "刷新"
                }
            ],
            "key": "deal"
        },
        "values": [
            {
                "id": "Electric001@1471419400813",
                "content": "2016-08-18 09:32:34"
            },
            {
                "id": "Electric001@1471419400813",
                "content": "2016-08-18 09:37:06"
            },
            {
                "id": "Electric001@1471419400813",
                "content": "2016-08-18 09:37:28"
            },
            {
                "id": "Electric001@1471419400813",
                "content": "2016-08-18 09:38:07"
            },
            {
                "id": "Electric001@1471419400813",
                "content": "2016-08-18 09:39:07"
            },
            {
                "id": "Electric001@1471419400813",
                "content": "2016-08-18 09:43:00"
            }
        ]
    };
     function SortArrayByDate(jsonArray) {
       var jsonArray2=[];
        for(var index in jsonArray){
            jsonArray2.push(jsonArray[index]);
        }
//核心代码,sort函数的构造
        jsonArray2.sort(function(json1,json2){
            var date1=json1["content"];
            var time1=new Date(date1).getTime();
            var date2=json2["content"];
            var time2=new Date(date2).getTime();
            return  time2-time1;
        });
         return jsonArray2;
    }
    var resulta= SortArrayByDate(jsonData.values);
    var a=[];
    for(var index in resulta){
        a.push(resulta[index].id+":"+resulta[index].content);
    }
    document.getElementById('div').innerHTML=a;
</script>
</html>
打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP