如何使用forEach()方法遍历对象数组?

时间:2018-05-31 15:11:59

标签: javascript arrays loops object

使用forEach()方法循环数组打印使用 console.log 输出以下甜甜圈摘要。< / p>

果冻甜甜圈每个售价1.22美元

巧克力甜甜圈每个售价2.45美元

苹果酒甜甜圈每个售价1.59美元

波士顿奶油甜甜圈每个售价5.99美元

&#13;
&#13;
var donuts = [
  { type: "Jelly", cost: 1.22 },
  { type: "Chocolate", cost: 2.45 },
  { type: "Cider", cost: 1.59 },
  { type: "Boston Cream", cost: 5.99 }
];
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:-2)

forEach()方法每个数组项执行一次回调函数。

forEach()循环的回调设置为控制台记录所需的值,您可以使用传递的参数(此处为e)访问它们。

&#13;
&#13;
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(e=> console.log(`
  ${e.type} donuts costs ${e.cost} each
`))
&#13;
&#13;
&#13;

答案 1 :(得分:-4)

查看文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

&#13;
&#13;
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(element) {
    console.log(element);
});
&#13;
&#13;
&#13;