The forin Loop


The for in Loop

Closely allied to the for loop is the for in loop, which iterates a variable over all the properties of an object. For each property, JavaScript executes the statements in the loop's body. That might sound a little dry, but in fact, it's a great help when you want to find out which properties are available to you in a specific object, such as some unknown browser's document object. It's also handy because you can iterate over all the properties in an object without even knowing how many properties there are, because the loop handles that automatically. Here's the syntax of this loop:

 for (variable in object) {  statements  } 

The following parts comprise this loop:

  • variable . Variable to use when iterating over every property.

  • object . Object you want the properties of.

  • statements . The statements to execute for each property.

The for in loop has been around for a long time, as you see in Table 3.2.

Table 3.2. The for in Loop

Statement

NS2

NS3

NS4

NS6

IE3a

IE3b

IE4

IE5

IE5.5

IE6

for in

x

x

x

x

x

x

x

x

x

x

Let's take a look at the document object in both the Netscape Navigator and Internet Explorer using a for in loop. We'll take a look not only at the various properties, but also the current value of those properties; to find the current values of each property, we can treat the document object as an array of properties, giving the property name as the array index. Here's what the code looks like:

(Listing 03-03.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Using the for...in Loop          </TITLE>      </HEAD>       <BODY>          <H1>Using the for...in Loop</H1>          <SCRIPT LANGUAGE="JavaScript">              <!--  for (var property in document) {   document.write(property + ": " + document[property] + "<BR>")   }  // -->          </SCRIPT>      </BODY>  </HTML> 

That's all it takes. You can see the results of this code in Figure 3.3 for the Netscape Navigator and in Figure 3.4 for the Internet Explorer. Try this example yourselfit's instructive to see how differently these two browsers report the properties of their document objects. For example, the Netscape Navigator lists not only properties but also the document object's methods (such as document.write ), whereas the Internet Explorer lists properties and event handlers (such as onclick ), but not any methods of its document object.

Figure 3.3. Displaying document object properties in the Netscape Navigator.

graphics/03fig03.gif

Figure 3.4. Displaying document object properties in the Internet Explorer.

graphics/03fig04.gif



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net