• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

3. Arrays and Objects > 3.4. Doing Something with the Items in an Array

Doing Something with the Items in an Array

NN 2, IE 3

Problem

You want to loop through all entries of an array and read their values.

Solution

Use a for loop to build an incrementing index counter, limited by the length of the array. Although not particularly practical, the following sequence demonstrates how to iterate through an array and reference individual entries of the array from inside the loop:

var myArray = ["Alice", "Fred", "Jean", "Steve"];
for (var i = 0; i < myArray.length; i++) {
    alert("Item " + i + " is:" + myArray[i] + ".");
}

The limit expression portion of the for loop uses the less-than (<) operator on the length property of the array. Because index values are zero-based, but the length property contains the actual count of items, you want to keep the maximum index value at one less than the count of items. Therefore, do not use the less-than or equal (<=) operator. If you want the loop to operate in reverse order, initialize the loop counter variable (i) to be the length minus 1:


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint