Array Loop Through using For(ICU)
/*
1. Store a open index var
2. You can create other vars to hold html tags to be used in final formatting
3. Create the array. here we have one with 4 elements
4. evoke your for loop
- I : create your sentry variable, use the same open index var you created
at step 1.
- C : While the index is less than the length property of fruits array,
execute the block
- U : And on each pass, update the index value.
This is going to update the index continously, until the condition that
the index is less than the array length is no longer true, then the loop exits.
In the block itself, each pass we are prepending to var 'text'
a list item tag, the value stored at the current referenced index, and
a closing list itme tag.
then we are going to concatenate the closing unordered list tag.
now its ready to go, being output to the inner html of an element.
*/
<!DOCTYPE html>
<html>
<body>
<p>The best way to loop through an array is using a standard for loop:</p>
<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>
</html>