- Detecting Browser Plug-ins
- Around and Around with Loops
- Writing with Loops
- Using For/In Loops
- Using Do/While Loops
- Checking if Java Is Enabled
- Functions
- Using Multi-level Conditionals
- Working with Functions That Return Values
- Handling Errors
- Putting More than One Script on a Page
- Scrolling Status Bars
- Status Bar Messages
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.
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
- 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.
-
document.write(j + ": " + 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.Figure 3.6 All the plug-ins and all their properties are shown in Netscape/Win.
Figure 3.7 The Internet Explorer/Mac plug-ins and properties are displayed, with some differences.
- } This closing brace ends the for/in loop.