我创建了一个像这样的对象。
myObj = {
"name":"John",
"age":30,
"cars": [
"car1":"Ford",
"car2":"BMW",
"car3":"Fiat"
]
}
我可以轻松阅读姓名和年龄,但我想阅读对象“cars”下的内容(键值)。我想在下拉列表中放置键值,这样如果从汽车中选择任何键,那么我将得到各自的值。 谢谢!
答案 0 :(得分:1)
只需按myObj.cars.car1
,myObj.cars.car2
和myObj.cars.car3
直接或循环播放,如下例所示
var myObj = {
"name": "John",
"age": 30,
"cars": {
"car1": "Ford",
"car2": "BMW",
"car3": "Fiat"
}
};
for (let i in myObj) {
if (typeof myObj[i] == 'object') {
for (let j in myObj[i]) {
console.log(j, myObj[i][j]);
}
} else {
console.log(i, myObj[i]);
}
}

答案 1 :(得分:0)
使用点运算符,您可以通过它来访问属性
myObj = {
"name":"John",
"age":30,
"cars": {
"car1":"Ford",
"car2":"BMW",
"car3":"Fiat"
}
}
console.log(myObj.cars.car1);
console.log(myObj.cars.car2);
console.log(myObj.cars.car3);