Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

Essential Javascript -- A Javascript Tutorial

By Patrick Hunlock
2007-12-02


JavaScript Loops: FOR/IN

Javascript has a variant of the for loop when dealing with Javascript objects.

Consider the following object…

var myObject = { 'animal' : 'dog',
                 
'growls' : true,
                 
'hasFleas': true,
                 
'loyal' : true } 

We can loop through these values with the following construct.

var myObject = { 'animal' : 'dog',
                 
'growls' : true,
                 
'hasFleas': true,
                 
'loyal' : true }
                 
for (var property in myObject) {
   document
.writeln(property + ' contains ' + myObject[property]+'<br>');
}                                  
// Outputs:
// animal contains dog
// growls contains true
// hasFleas contains true
// loyal contains true

What this essentially does is assign the property name to the variable property. We can then access myObject through an associative array style syntax. For instance the first itteration of the loop assigns animal to property and myObject["animal"] will return dog.

There is a big caveat here in that properties and methods added by prototyping will also show up in these types of loops. Therefore it's best to always check to make sure you are dealing with data and not a function as such…

for (var property in myObject) {
   
if (typeof(myObject[property]) != 'function') {
      document
.writeln(property + ' contains ' + myObject[property]+'<br>');
   
}
} 

The typeof check to screen out functions will ensure that your for/in loops will extract only data and not methods that may be added by popular javascript libraries like Prototype.



Tutorial Pages:
» Essential Javascript -- A Javascript Tutorial
» Getting Started
» In-Line Javascript
» External Javascript
» Javascript is case sensitive
» Output (writeln)
» Output (alert)
» Output (getElementById)
» Input (One Click To Rule Them All)
» Input (User Input)
» Javascript is an Event Driven Language
» Comments
» Variables
» Variable Scope
» Special Keywords
» Arithmetic Operators
» Logical and Comparison Operators
» JavaScript Conditionals: IF
» JavaScript Conditionals: SWITCH
» JavaScript Conditionals: Shorthand Assignment
» JavaScript Conditionals: Ternary Operators
» JavaScript Loops: FOR
» JavaScript Loops: FOR/IN
» JavaScript Loops: WHILE
» Bringing It All Together
» DHTML: Dynamic HTML
» Conclusion


copyright © 2006, 2007 by Patrick Hunlock


 | Bookmark
Related Tutorials:
» JavaScript Debugging Techniques with Firebug
» Striped Tables Using JavaScript
» Opening PDFs in a New Window with JavaScript
» Submit Forms Conditionally using JavaScript
» How to Setup a Randomising Function
» Introduction to JavaScript Tutorial