Looping through object properties and hash tables using the “in” statement
As I said earlier, objects are hash tables of properties and functions so looping throught them is done the same way (weepee!).
The “in” statement
The in statement must be used in a for loop. Like this : for (var element in allElements). In most of the other languages, the element variable would contain the complete element but in javascript, it contains the name that refers to the complete element.
Looping through a hash table
Before doing it, maybe you should take a look at How to use javascript hashes (or hash-table) to make sure you fully understand what are javascript hash tables.
[source:javascript]
// I create a hash table
var hashPetNames = new Object();
// I create the pets
hashPetNames["cat"] = “Mistigri”;
hashPetNames["dog"] = “Rex”;
hashPetNames["bird"] = “Bibi”;
// I loop using the “in” statement
for (var name in hashPetNames) {
alert(“My ” + name + “‘s name is ” + hashPetNames[name]);
}
[/source]
Run this code and you should see the alerts :
- My cat‘s name is Mistigri.
- My dog‘s name is Rex.
- My bird‘s name is Bibi.
So easy.
Looping through an object
This one is a little kinkier. Why would I want to loop through an object properties and methods? I can’t give you an answer. It’s up to you to find it. I’ve used it a couple of times so it’s not as useless as you could think.
Example, I would like to separatly alert all the properties and methods of an object.
[source:javascript]
// Create the class
function TheClass() {
this.name = “The class”;
this.fullName = “The full name of the class”;
this.age = “51″;
}
// Add a function
TheClass.prototype.alertClass = function() {
alert(this.name + ” ” + this.fullName + this.Age);
}
// Construct the object
var theObject = new TheClass();
// Loop through the properties/functions
var properties = “”;
for (var propertyName in theObject) {
// Check if it’s NOT a function
if (!(theObject[propertyName] instanceof Function)) {
properties += propertyName + “, “;
}
}
alert(“Properties : ” + properties);
// Loop through the properties/functions
var functions = “”;
for (var functionName in theObject) {
// Check if it’s a function
if (theObject[functionName] instanceof Function) {
functions += functionName + “, “;
}
}
alert(“Functions : ” + functions);
[/source]