首页 > 代码库 > 嵌套 JSON 对象中的数组使用 for-in 来循环访问每个数组

嵌套 JSON 对象中的数组使用 for-in 来循环访问每个数组

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>

<p>循环内嵌数组:</p>

<p id="demo"></p>

<script>

var myObj, i, j, x = "";
myObj = {
    "name":"网站",
    "num":3,
    "sites": [
        { "name":"Google", "info":[ "Android", "Google 搜索", "Google 翻译" ] },
        { "name":"Runoob", "info":[ "菜鸟教程", "菜鸟工具", "菜鸟微信" ] },
        { "name":"Taobao", "info":[ "淘宝", "网购" ] }
    ]
}

for (i in myObj.sites) {
    x += "<h1>" + myObj.sites[i].name + "</h1>";
    for (j in myObj.sites[i].info) {
        x += myObj.sites[i].info[j] + "<br>";
    }
}

document.getElementById("demo").innerHTML = x;

</script>

</body>
</html>

  

嵌套 JSON 对象中的数组使用 for-in 来循环访问每个数组