Get Programming with JavaScript - Listing 8.07
Listing 8.07 - Iterating over an array with forEach
JS Bin
var items;
var showInfo;
items = [
"The Pyramids",
"The Grand Canyon",
"Bondi Beach"
];
showInfo = function (itemToShow) {
console.log(itemToShow);
};
items.forEach(showInfo);
Further Adventures
Listing 8.07 - Iterating over an array with forEach - Task 1
- Add a few extra items to the array, some using push and some using square brackets.
var items;
var showInfo;
items = [
"The Pyramids",
"The Grand Canyon",
"Bondi Beach"
];
showInfo = function (itemToShow) {
console.log(itemToShow);
};
items.push("The Taj Mahal");
items.push("Popocatépetl");
items[items.length] = "The Tower of London";
items[items.length] = "Old Faithful";
items.forEach(showInfo);
Listing 8.07 - Iterating over an array with forEach - Task 2
- Update the showInfo function to also display the number of letters in each item.
var items;
var showInfo;
items = [
"The Pyramids",
"The Grand Canyon",
"Bondi Beach"
];
showInfo = function (itemToShow) {
console.log(itemToShow + " has " + itemToShow.length + " letters");
};
items.forEach(showInfo);
Listing 8.07 - Iterating over an array with forEach - Task 3
- Write a new function that finds the total number of letters of the elements in the items array.
var items;
var getNumLetters; // declare a variable
items = [
"The Pyramids",
"The Grand Canyon",
"Bondi Beach"
];
// define a function and
// assign it to the variable
getNumLetters = function (itemsArray) {
var runningTotal = 0;
itemsArray.forEach(function (item) {
runningTotal += item.length;
});
return runningTotal;
};
// test the function
console.log("Total letters = " + getNumLetters(items));