所以我有一个带有嵌套对象的数组,我想用forEach()
方法来遍历它。最后,我希望有4个看起来像这样的句子:
我以为我需要一个内部循环来解决各个项目,但是我不确定。非常感谢您的帮助。到目前为止,这是我的代码:
var donuts = [
{ type: "Jelly", cost: 1.22 },
{ type: "Chocolate", cost: 2.45 },
{ type: "Cider", cost: 1.59 },
{ type: "Boston Cream", cost: 5.99 }
];
donuts.forEach(function(elem) {
for (i=0; i<elem.length; i++) {
let type = donuts[i].type
let cost = donuts[i].cost
console.log(type + " donuts cost $" + cost + " each");
}
});
答案 0 :(得分:1)
forEach()为数组中的每个元素调用一次提供的回调函数。甜甜圈是代表各个甜甜圈的javascript对象数组。
var donuts = [{
type: "Jelly",
cost: 1.22
},
{
type: "Chocolate",
cost: 2.45
},
{
type: "Cider",
cost: 1.59
},
{
type: "Boston Cream",
cost: 5.99
}
];
donuts.forEach(function(donut) {
console.log(donut.type + " donuts cost $" + donut.cost + " each");
});