访问嵌套的 JSON 数组

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <h1>JSON 数组</h1>
  6.  
  7. <p>遍历数组内的数组。</p>
  8.  
  9. <p id="demo"></p>
  10.  
  11. <script>
  12. var myObj, i, j, x = "";
  13. myObj = {
  14. "name":"Bill Gates",
  15. "age":62,
  16. "cars": [
  17. {"name":"Porsche", "models":["911", "Taycan"]},
  18. {"name":"BMW", "models":["M5", "M3", "X5"]},
  19. {"name":"Volvo", "models":["XC90", "V60"] }
  20. ]
  21. }
  22. for (i in myObj.cars) {
  23. x += "<h2>" + myObj.cars[i].name + "</h2>";
  24. for (j in myObj.cars[i].models) {
  25. x += myObj.cars[i].models[j] + "<br>";
  26. }
  27. }
  28. document.getElementById("demo").innerHTML = x;
  29. </script>
  30.  
  31. </body>
  32. </html>