Javascript 打印出具有关键帧和值的所有对象
我正在做一个需要打印所有对象的项目,我必须使用嵌套for in循环 结果应该这样打印:Javascript 打印出具有关键帧和值的所有对象,javascript,Javascript,我正在做一个需要打印所有对象的项目,我必须使用嵌套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: "Manches
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次,因为有外环和内环。我似乎无法打印每个内部对象,因为它总是打印
名称
,我尝试添加容量
,主页
,和远离
,但它从不打印它们,所以我必须将它们从代码中删除。有没有一种方法可以动态打印所有外部对象和内部对象,而不必重复8次 试试这个:
const
俱乐部={
球队:“曼联”,
体育场:{
名称:'山谷',
容量:65000
},
联盟:“联盟1”,
套件:{
家:“蓝色和白色”,
客场:“浅蓝色”
}
},
结果=对象。条目(俱乐部)。地图([键,值])=>
键+':'+(值的类型=='string'?
价值:
Object.entries(value).map([innerKey,innerValue])=>
`\n\t${innerKey}:${innerValue}`)。连接(“”))
).join('\n');
console.log(结果)
尝试以下操作:
const
俱乐部={
球队:“曼联”,
体育场:{
名称:'山谷',
容量:65000
},
联盟:“联盟1”,
套件:{
家:“蓝色和白色”,
客场:“浅蓝色”
}
},
结果=对象。条目(俱乐部)。地图([键,值])=>
键+':'+(值的类型=='string'?
价值:
Object.entries(value).map([innerKey,innerValue])=>
`\n\t${innerKey}:${innerValue}`)。连接(“”))
).join('\n');
console.log(结果)
对代码的轻微更改。在内部循环中导航之前,只需检查值是否为object。当前代码中的问题是,因为in
循环正在遍历字符串值
功能足球俱乐部(){
让俱乐部={
球队:“曼联”,
体育场:{
名称:“山谷”,
容量:65000
},
联盟:“联盟1”,
套件:{
家:“蓝色和白色”,
客场:“浅蓝色”
}
};
为了(让奥特基加入俱乐部){
if(俱乐部类型[outerKey]!=“字符串”){
对于(让innerKey进入俱乐部[outerKey]){
console.log(
outerKey+“:“+innerKey+”:“+club[outerKey][innerKey]
);
}
控制台日志(“”);
}否则{
console.log(outerKey+:“+club[outerKey]);
控制台日志(“”);
}
}
}
足球俱乐部()代码>对代码的细微更改。在内部循环中导航之前,只需检查值是否为object。当前代码中的问题是,因为in
循环正在遍历字符串值
功能足球俱乐部(){
让俱乐部={
球队:“曼联”,
体育场:{
名称:“山谷”,
容量:65000
},
联盟:“联盟1”,
套件:{
家:“蓝色和白色”,
客场:“浅蓝色”
}
};
为了(让奥特基加入俱乐部){
if(俱乐部类型[outerKey]!=“字符串”){
对于(让innerKey进入俱乐部[outerKey]){
console.log(
outerKey+“:“+innerKey+”:“+club[outerKey][innerKey]
);
}
控制台日志(“”);
}否则{
console.log(outerKey+:“+club[outerKey]);
控制台日志(“”);
}
}
}
足球俱乐部()
这篇文章可能会有帮助,这能回答你的问题吗?这篇文章可能有助于回答你的问题吗?