Thursday 19 August 2010

Equivalent to foreach in javascript

I happily developed in C# for a number of years during my time at Hewlett-Packard Labs. One of my favourite basic language features was the foreach function, for quickly iterating through the items in any type of collection.

foreach (MyObject ob in myObjects) {
ob.doSomething();
}


I started developing seriously in javascript a few months back, and eventually discovered a similar function..

var list = ["a","b","c"];
for( var i in list) {
console.log( list[i] );
}
// outputs a b c


Now it's not quite so neat as the C# version, as you get the index of the element in the array, rather than the element itself. This means you need to use the index to get the element out of the array - the array[i] part here.

You can also iterate all the properties of an object too.
var ob = {a:1,b:2,c:3};
for( var name in ob) {
alert( ob[name] );
}
// outputs 1 2 3

Run it here

However, there's a nasty gotcha with this approach. If someone anywhere in your javascript app, or any of the libraries it uses, or any code eval'd at runtime adds any properties or functions to 'Object' or 'Array' then your for in loop will return that property too!
This is of course, insane, but it's just how Javascript works. There's a great example of this problem if you use jsfiddle, a fab site for testing ideas using the 'holy trinity' of HTML, CSS, and Javascript. The libraries it uses add a whole bunch of stuff to Array including their own 'foreach' function.

Click here to see

Happily, there's a simple solution - just use the 'hasOwnProperty' method on an object to check that a property is not one inherited from the base class.

var foo = [1,2,3];
for( var i in foo) {
if (foo.hasOwnProperty(i)) {
alert( foo[i] );
}
}​


Click here to see

This is just one of the odd things in Javascript that can mess you around quite badly if you don't know about it!

No comments:

Post a Comment