Loops are handy, if you want to run the same code over and over again, each time with a different value. Often this is the case when working with arrays. The best way to loop through an array, is by using a standard "for" loop. So, instead of writing: text += fruits[0] + "<br>";
text += fruits[1] + "<br>";
text += fruits[2] + "<br>";
text += fruits[3] + "<br>";
You can write: for (i = 0; i < fruits.length; i++) {text += fruits[i] + "<br>";}
HTML file:
Displayed by browser:
<body>
<h4>Loop through an array until all elements in the array print to a list:</h4>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var index;
var text = "<ul>";
var fruits = ["Banana", "Orange", "Apple", "Mango"];
for (index = 0; index < fruits.length; index++) {
text += "<li>" + fruits[index] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
Loop through an array until all elements in the array print to a list:
The ++ will add one increment to the index number, repeating the loop over and over, until it's done the entire length of the array.