对象JSON中的invoque数组

时间:2017-09-24 09:22:19

标签: javascript json

我在对象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对象的数组值:          测试

1 个答案:

答案 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>