我在对象JSON中有invoque数组Object,但我调用了最后一个索引
var myObj, x, i, y;
myObj = {
"name": "John",
"age": 30,
"cars": [{
"n": "Ford",
"a": "BMW",
"c": "Fiat"
}, {
"n": "test",
"a": "BMWwww",
"c": "Fiattt"
}]
};
x = myObj.cars[0]["n"];
for (y in myObj.cars) {
document.getElementById("demo").innerHTML = myObj.cars[y].n;
}
<p>Access an array value of a JSON object:</p>
<p id="demo"></p>
但我有显示
访问JSON对象的数组值: 测试
答案 0 :(得分:0)
您正在覆盖innerHTML
的值。您可以添加值和换行符标记。
然后我建议使用一个带有索引变量的简单for
循环来使用。你可能会在这里成为一个懒人:JavaScript Loops: for…in vs for
var myObj = { name: "John", age: 30, cars: [{ n: "Ford", a: "BMW", c: "Fiat" }, { n: "test", a: "BMWwww", c: "Fiattt" }] },
i;
for (i = 0; i < myObj.cars.length; i++) {
document.getElementById("demo").innerHTML += myObj.cars[i].n + '<br>';
}
<p>Access an array value of a JSON object:</p>
<p id="demo"></p>