【发布时间】:2020-05-24 12:20:38
【问题描述】:
我正在做一个需要我打印出所有对象的项目,我必须使用嵌套 for in 循环。
结果应该是这样打印的:
team: Manchester United
stadium:
name:The Valley
capacity:65000
league: League 1
kit:
home: blue and white
away:light blue`
这是我想出的:
function footballClub() {
let club = {
team: "Manchester United",
stadium: {
name: "The Valley",
capacity: 65000
},
league: "League1",
kit: {
home: "blue and white",
away: "light blue"
}
}
for (let outerKey in club) {
for (let innerKey in club[outerKey]) {
if (typeof club[outerKey === club.stadium.hasOwnProperty('name')]) {
console.log(outerKey + ": " + innerKey + ": " + club[outerKey].name);
}
console.log(outerKey + ": " + club[outerKey]);
}
}
}
我被卡住了,因为它只是重复了球队、体育场等 8 次,因为外部和内部循环。
我似乎无法打印每个内部对象,因为它总是打印name,我尝试添加capacity、home 和away,但它从不打印它们,所以我必须删除它们来自代码。
有没有办法动态地打印所有外部对象和内部对象并且不重复 8 次?
【问题讨论】:
-
这篇文章可能对stackoverflow.com/questions/8312459/…有帮助
-
这能回答你的问题吗? Get all keys of a nested dictionary
标签: javascript