如何使用.forEach正确访问数组中的对象?

jer*_*ern -1 javascript arrays object

对于一个测验,我得到了一个包含对象的数组:

var donuts = [
{ type: "Jelly", cost: 1.22 },
{ type: "Chocolate", cost: 2.45 },
{ type: "Cider", cost: 1.59 },
{ type: "Boston Cream", cost: 5.99 }
];
Run Code Online (Sandbox Code Playgroud)

我的工作是使用.forEach方法遍历数组中的对象.好吧,我基本上攻击它并制作了一个迭代变量来帮助我使用索引来访问每个对象.

var i = 0;
donuts.forEach(function(donutSummary) {

var donut = donuts[i].type;
var cost = donuts[i].cost;

console.log(donut + " donuts cost $" + cost + " each");
i = i + 1;
});
Run Code Online (Sandbox Code Playgroud)

在我的代码顶部,我声明并为我的索引分配了一个变量i.我知道必须有一种更好的方法来访问这个数组中的对象.

谁能告诉我在不使用迭代变量的情况下执行此操作的正确方法是什么?

谢谢!

Cer*_*nce 6

使用提供的函数forEach,它的第一个参数是迭代的当前项.该函数将被调用数组中的每个项目,所以你只需要逐一接入各家的性质donutconsole.log他们.请参阅forEach上的MDN文档.

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

donuts.forEach(({ type, cost }) => console.log(`${type} donuts cost $${cost} each`));
Run Code Online (Sandbox Code Playgroud)

或者,如果您不能使用解构和ES6语法:

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')
});
Run Code Online (Sandbox Code Playgroud)

  • 是的,破坏会降低语法噪音,因此通常更可取 - 如果您只需要访问对象的某些特定属性而不需要整个对象,请使用解构将属性提取到变量中,而不是仅使用一个对象目的是稍后分解. (2认同)