JS写法如下:
const myObj = { name: "John", age: 30, cars: [ { name: "Ford", models: ["Fiesta", "Focus", "Mustang"] }, { name: "BMW", models: ["320", "X3", "X5"] }, { name: "Fiat", models: ["500", "Panda"] } ] } //官方例子写法 let x = ""; for (let i in myObj.cars) { x += "<h1>" + myObj.cars[i].name + "</h1>"; for (let j in myObj.cars[i].models) { x += myObj.cars[i].models[j] + "<br>"; } } document.getElementById("demo").innerHTML = x; //存疑写法,如果只想models里的数值一次性输出,是不是可以少写一次循环? let y = ""; for (let i in myObj.cars) { y += "<h1>" + myObj.cars[i].name + "</h1>"; y += myObj.cars[i].models + "<br>"; } document.getElementById("demo2").innerHTML = y;
1. 官方例子测试结果如下:
2. 存疑例子测试如下:
标签:name,models,cars,JS,嵌套,let,数组,myObj From: https://www.cnblogs.com/keeplearningandsharing/p/18361386