Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
This chapter is from the book

Using For/In Loops

(Netscape and Internet Explorer/Mac)

The previous example shows how to use JavaScript to write with a loop, but the way it's written demands that you know in advance the names of the objects you'll be displaying. Unfortunately, that's not always the case. In Script 3.4 , we use the for/in loop construction to display whatever the object's properties happen to be. The for/in loop checks for all the properties in a specified object.

03fig09.jpg

Script 3.4 This type of loop allows you to display objects when you don't even know what they are.

To use a for/in loop

  1. for (j in thisPlugin) { The variable thisPlugin, as in the previous example, is set to the current plug-in that we're processing. Instead of just writing out, for example, thisPlugin.filename, we instead use a for/in loop to look at every property that thisPlugin contains. Because i is already in use in the outer loop, we use our next choice of loop variable name, j. Each time we go around the loop, j will be set to the name of the next property of the thisPlugin object. It's important to note that j is not a number; unlike i, it's a string, even though it's a loop variable.
  2. document.write(j + ": " +
    U2192.GIF thisPlugin[j] + "<br \/>")
    
    Inside the loop, we can use j (the name of the property) and thisPlugin[j] (the value of that property) to display all the properties of the user's plug-ins on our page. Figure 3.6 (Netscape/Win) and Figure 3.7 (Internet Explorer/Mac) show one of the main reasons why this functionality is so useful: the plugin object on each platform differs from the other. The former has item and namedItem properties that the latter doesn't, but this script happily displays both.
    03fig10.gif

    Figure 3.6 All the plug-ins and all their properties are shown in Netscape/Win.

    03fig11.jpg

    Figure 3.7 The Internet Explorer/Mac plug-ins and properties are displayed, with some differences.

  3. } This closing brace ends the for/in loop.
  • + Share This
  • 🔖 Save To Your Account