如何在 JavaScript 中访问嵌套的 json 对象?
javascriptobject oriented programmingfront end technology更新于 2025/4/7 8:12:17
访问嵌套的 json 对象就像访问嵌套数组一样。嵌套对象是位于另一个对象内的对象。
在下面的例子中,"vehicles"是一个位于名为"person"的主对象内的对象。使用点符号可以访问嵌套对象的属性(car)。
示例 1
<html>
<body>
<script>
var person = {
"name":"Ram",
"age":27,
"vehicles": {
"car":"limousine",
"bike":"ktm-duke",
"plane":"lufthansa"
}
}
document.write("Mr Ram has a car called" + " " + person.vehicles.car);
</script>
</body>
</html>
输出
Mr Ram has a car called limousine
示例 2
在下面的示例中,名为"air-lines"的对象是双重嵌套(嵌套在嵌套对象内)。该双重嵌套对象(lufthansa)的属性可通过点符号访问,如下所示。
<html>
<body>
<script>
var person = {
"name":"Ram",
"age":27,
"vehicles": {
"car":"limousine",
"bike":"ktm-duke",
"airlines":{
"lufthansa" : "Air123",
"British airways" : "Brt707"
}
}
}
document.write("Mr Ram travels by plane called" + " " + person.vehicles.airlines.lufthanza);
</script>
</body>
</html>
输出
Mr Ram travels by plane called Air123
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

