简体   繁体   中英

How to use forEach method for objects in array in JavaScript?

Here is an array of donut objects.

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

Directions: Use the forEach() method to loop over the array and print out the following donut summaries using console.log.

Jelly donuts cost $1.22 each
Chocolate donuts cost $2.45 each
Cider donuts cost $1.59 each
Boston Cream donuts cost $5.99 each

I wrote this code but it doesn't work:

donuts.forEach(function(donut) {

    console.log(donuts.type + " donuts cost $" + donuts.cost + " each");

});

What's wrong?

Instead of

donuts.forEach(function(donut) {

    console.log(donuts.type + " donuts cost $" + donuts.cost + " each");

});

change it to

donuts.forEach(function(donut) {

    console.log(donut.type + " donut cost $" + donut.cost + " each");

});

You are looping through the donuts array and calling each object a donut , but in your code, you are still trying to reference donuts .

donuts.forEach(function(donut) { console.log( ${donut.type} donut costs $${donut.cost} each )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM