Looping with the Array.forEach method
EasyProgramming.net tutorial on the array.forEach method
by dshilkret
HTML
<!-- Easy JavaScript #26 - the forEach method-->
<p>
Welcome to the 26th Easy JavaScript tutorial, part of <a href="http://www.easyprogramming.net" target="_blank">EasyProgramming.net</a>. This tutorial covers the <code>forEach</code> array method as part of our coverge of JavaScript loops!
</p>
<p>
The <code>forEach</code> method iterates through each array item and executes a block of code. It will complete when it has gone through every item in the array.
</p>
<h2>
Syntax of the <code>forEach</code> method:
</h2>
<pre>
array.forEach(function(item, index){
execute code;
the 'item' is the actual value;
'index' is the index number (e.g. i);
})
</pre>
<h3>Output:</h3>
<p>
<span id="output"></span>
</p>
<p>
W3Schools: <a href="http://www.w3schools.com/jsref/jsref_forEach.asp" target="_blank">http://www.w3schools.com/jsref/jsref_forEach.asp</a>
</p>
JavaScript
//iterate through each array item with forEach
var myArray = ['Boston','New York','Chicago','Miami','Los Angeles','Dallas','Seattle'];
myArray.forEach(function(item,i){
document.getElementById("output").innerHTML += (i+1) + ": " + item + "<br />";
});