Get Programming with JavaScript - Listing 8.10
Listing 8.10 - Using the arguments passed by forEach - compact
JS Bin
[ "Dax", "Jahver", "Kandra" ].forEach(function (item, index, wholeArray) {
console.log("Item: " + item);
console.log("Index: " + index);
console.log("Array: " + wholeArray);
});
Further Adventures
Listing 8.10 - Using the arguments passed by forEach - compact - Task 1
- Create an array of rectangle objects. Each rectangle should have a length property and a width property.
var rectangles = [
{
length: 10,
width: 6
},
{
length: 8,
width: 7
},
{
length: 2.5,
width: 2.5
}
];
Listing 8.10 - Using the arguments passed by forEach - compact - Task 2
- Define an assignArea function that takes a rectangle as an argument and assigns an area property holding the area of the rectangle.
var rectangles = [
{ length: 10, width: 6 },
{ length: 8, width: 7 },
{ length: 2.5, width: 2.5 }
];
var assignArea = function (rect) {
rect.area = rect.length * rect.width;
};
Listing 8.10 - Using the arguments passed by forEach - compact - Task 3
- Define a showInfo function that takes a rectangle as an argument and displays its properties on the console.
var rectangles = [
{ length: 10, width: 6 },
{ length: 8, width: 7 },
{ length: 2.5, width: 2.5 }
];
var assignArea = function (rect) {
rect.area = rect.length * rect.width;
};
var showInfo = function (rect) {
var info = "The rectangle with length " + rect.length;
info += " and width " + rect.width;
info += " has area " + rect.area;
console.log(info);
};
Listing 8.10 - Using the arguments passed by forEach - compact - Task 4
- Use forEach and your two functions to display info about each of the rectangles in the array.
var rectangles = [
{ length: 10, width: 6 },
{ length: 8, width: 7 },
{ length: 2.5, width: 2.5 }
];
var assignArea = function (rect) {
rect.area = rect.length * rect.width;
};
var showInfo = function (rect) {
var info = "The rectangle with length " + rect.length;
info += " and width " + rect.width;
info += " has area " + rect.area;
console.log(info);
};
rectangles.forEach(function (rect) {
assignArea(rect);
showInfo(rect);
});