Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Using for...in loops

A third type of loop is available in JavaScript. The for...in loop is not as flexible as an ordinary for or while loop. Instead, it is specifically designed to perform an operation on each property of an object.

For example, the navigator object contains properties that describe the user's browser, as you'll learn in Hour 14, "Creating Cross-Browser Scripts." You can use for...in to display this object's properties:

for (i in navigator) {
document.write("property: " + i);
document.write(" value: " + navigator[i] + "<br>");
}

Like an ordinary for loop, this type of loop uses an index variable (i in the example). For each iteration of the loop, the variable is set to the next property of the object. This makes it easy when you need to check or modify each of an object's properties.

Share ThisShare This

Informit Network