我可以访问内部属性,但似乎无法弄清楚如何访问集合的名称。例如,在下面的代码中,我可以得到行星地球的值,但我无法弄清楚如何显示地球名称
var planet = {
Earth: [
'water',
'rock'
]
};
alert(**output Key/Earth ** + " consists of " planet.Earth[0] + " & " + planet.Earth[1]);
我也试过这个。我可以获得类型和位置,但不能显示行星本身,如“地球”或“维纳斯”。我得到[undefined]或[object object]
var planets = {
"Earth": {type: "Terrestrial ", location: "Milky Way"},
"Venus": {type: "Terrestrial", location: "Milky Way"}
};
alert("Planet: " + planets[0] + " TYPE: " + planets.Earth.type + "LOCATION: " + planets.Earth.location);
答案 0 :(得分:0)
您可以使用Object.enteries
。它从object返回一个数组。
height

您也可以使用Object.keys
var planets = {
"Earth": {type: "Terrestrial", location: "Milky Way"},
"Venus": {type: "Terrestrial", location: "Milky Way"}
};
var arr = Object.entries(planets);
arr.forEach((obj) => {
console.log("Planet: " + obj[0] + " TYPE: " + obj[1].type + " LOCATION: " + obj[1].location);
});