Iterating Through Collections

Arrays is something that you will find in programming language very often. The most common thing you can do with an array is to iterate or loop through every element in it.

var myArray = [1, 2, 3, 4]

//setup the index
var i = 0;

while (i < myArray.length)
{
    alert(myArray[i]);

    //increment the index
    i++;
}

As you can see, it's very easy to do, you just have to use the basic while loop. Length is method that will returning the number of elements in an array. If you want to use For loop, you can write it like this :

var myArray = [1, 2, 3, 4];

for(var i=0; i<myArray.length; i++)
{
    alert(myArray[i]);
}

Using the length method is very useful because we don't have to know how big the array is. You can add element inside your array however you like and this loop will still works.

results matching ""

    No results matching ""