HTML and CSS Reference
In-Depth Information
Using the forEach method
The forEach method enables an application to process some logic against each item in the
array. This method runs for every single item and doesn't produce a return value. forEach has
the same signature as the other methods you've seen so far in this section. The following code
demonstrates the forEach method:
var sportsArray = ['soccer', 'basketball', 'hockey', 'football', 'cricket', 'rugby'];
sportsArray.forEach(offerSport);
function offerSport(value, index, array) {
var sportsList = document.getElementById("sportsList");
var bullet = document.createElement("li");
bullet.innerText = value;
sportsList.appendChild(bullet);
}
In this sample, the code assumes that a list element on the HTML page is ready to be filled
with the list of sports, each formatted as a child node. Each element in the list is passed to the
function and added as an < li> element. The array elements aren't sorted in this case. You can
chain the methods together to ensure that the elements are, for example, alphabetized:
sportsArray.sort().forEach(offerSport);
Like with all the advanced methods shown thus far, the elements are passed to the func-
tion in ascending index order. So you could call the sort method and chain it together with
the forEach method to ensure that the elements are displayed to the user in order.
Using the ilter method
The ilter method provides a way to remove items for an array based on some processing
done in the callback function. The ilter method returns a new array containing the elements
that are included based on a return value of true or false from the callback function. In the
even number example, you can use the ilter method to scrub the array and ensure that the
program continues to use only an array that contains even numbers, as demonstrated here:
var evenNumbers = new Array(0, 2, 4, 6, 8, 9, 10, 12);
var allEven = evenNumbers.filter(evenNumberCheck, evenNumbers);
//work with the even numbers....
function evenNumberCheck(value, index, array) {
return (value % 2) == 0;
}
In this example, the evenNumberCheck method is the same as the one used previously.
However, rather than use the every or any method to determine the quality of the data with
respect to containing only even numbers, the ilter method simplifies the removal of the
odd numbers. You can use any logic in the callback function to process the element and
determine whether it should be included in the returned array, such as pattern matching or a
database lookup.
 
 
Search WWH ::




Custom Search