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>

猜你喜欢

转载自blog.csdn.net/W_violet/article/details/83504830