如果这是我的目标:
var obj = {
bakery1: {
small: {
name: "Small cookie",
price: 0.75;
}
large: {
name: "Large cookie",
price: 3.00;
}
}
bakery2: {
small: {
name: "Small cookie",
price: 1.00;
}
large: {
name: "Large cookie",
price: 4.00;
}
}
};
我将如何制作一个将每个价格打印到控制台的循环?
当这个值被打印出来时,有没有办法追踪这个名字?
例如,如果输出是 3.00,我该如何创建一个函数来给出与 3.00 价格相符的名称?
提前致谢!
回答你的问题:
function printPrice(obj) {
if (obj.price)
console.log(obj.name, obj.price)
else for (key in obj)
printPrice(obj[key])
}
var obj = {
"bakery1": {
"small": {
"name": "Small cookie",
"price": 0.75
},
"large": {
"name": "Large cookie",
"price": 3
}
},
"bakery2": {
"small": {
"name": "Small cookie",
"price": 1
},
"large": {
"name": "Large cookie",
"price": 4
}
}
};
printPrice(obj)
但是,对于这些类型的集合,最好使用数组。例如,我们可以这样做:
var bakeries = [
{
name: 'Bakery 1',
menu: [
{name: 'small cookie', price: 0.75},
{name: 'large cookie', price: 3.00}
]
},
{
name: 'Bakery 2',
menu: [
{name: 'small cookie', price: 1.00},
{name: 'large cookie', price: 4.00}
]
}
]
这使我们能够更好地组织每个项目的具体属性。在这种情况下,打印价格的代码变得简单得多:
bakeries
.map(bakery => bakery.menu)
.forEach(menu => menu.map(
item => console.log(item.name, item.price)))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)