home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Previous Section Next Section

3.4 Doing Something with the Items in an Array

NN 2, IE 3

3.4.1 Problem

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

3.4.2 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:

for (var i = myArray.length - 1; i >= 0; i--) {
    alert("Item " + i + " is:" + myArray[i] + ".");
}

You don't have to redeclare the counter variable with the var statement if you have initialized it in a separate var statement or in a previous loop earlier within the same function.

3.4.3 Discussion

It's not uncommon to loop through an array (or collection of DOM objects) to find a match for some value within the array, and then use the index of the found item to assist with other lookup tasks. For example, the following parallel (but distinctly separate) arrays contain data with individuals' names and their corresponding ages:

var nameList = ["Alice", "Fred", "Jean", "Steve"];
var ageList = [23, 32, 28, 24];

You can use these parallel arrays as a lookup table. The following function receives a name string as a parameter, and looks for the matching age in the second array:

function ageLookup(name) {
    for (var i = 0; i < nameList.length; i++) {
        if (nameList[i] =  = name) {
            return ageList[i];
        }
    return "Could not find " + name + ".";
}

Similarly, you can examine a property of objects within a collection, and use the "found" index to read or write properties of the target items. The following function empties all of the text boxes on a page, even if the page contains multiple forms:

function clearTextBoxes( ) {
    var allInputs = document.getElementsByTagName("input");
    for (var i = 0; i < allInputs.length; i++) {
        if (allInputs[i].type =  = "text") {
            allInputs[i].value = "";
        }
    }
}

For a multidimensional array, you need a multidimensional (i.e., nested) for loop construction to access each item. For example, given the two-dimensional array demonstrated in Recipe 3.2, the following nested for loops are able to reference each item and accumulate the numeric values from all entries of the two-dimensional array:

var total = 0;
for (var i = 0; i < salesArray.length; i++) {
    for (var j = 0; j < salesArray[i].length; j++) {
        total += salesArray[i][j];
    }
}

The nested array uses a separate loop counting variable (j). If you visualize the multidimensional array as the table shown in Recipe 3.2, the outer-counting variable (i) works along the rows, and the nested counting variable (j) works down the columns. Thus, the sequence of operations in this construction goes across the rows of the corresponding table as follows:

row 0, cell 0
row 0, cell 1
row 0, cell 2
row 0, cell 3
row 1, cell 0
row 1, cell 1
...

3.4.4 See Also

Recipe 3.9 for a speedy alternative to parallel array lookups using a simulated hash table; Recipe 3.2 for creating a multidimensional array.

    Previous Section Next Section