1. 程式人生 > >json資料的迴圈遍歷

json資料的迴圈遍歷

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="lib/jquery-3.1.1.min.js"></script>
    <script>
        window.onload=function(){
            //宣告資料,填充資料
            var user=[{"username":"青蓮劍仙","gender":"男","age":"19","address":"清幽居"}
            ,{"username":"詩仙李太白","gender":"男","age":"21","address":"幽居"}];
            //遍歷資料
            for(var value in user)
            {
                for(var i in user[value]){
                    console.log(i + " " + user[value][i])//json是健值對的形式賦值,這裡的i代表的是key,
                }
            } 
            //jquery的each函式遍歷json中的資料
            //each函式的第一個引數是需要遍歷的資料或者物件
            //第二個引數是一個函式,函式的i代表key,也就是索引,n代表與key對應的value值
            //外層迴圈控制物件的個數
//            for(var j=0;j<user.length;j++)
//            {
//                $.each(user, function(i, n){
//                    console.log( i , n );
//                });
//            }
            $.each(user,function(index,value){
                $.each(value,function(i,n){
                    console.log( i , n );
                })
            });
        }
    </script>
</head>

<body>

</body>
</html>