Javascript foreach loop solution

How to obtain a foreach loop like PHP in Javascript.
Posted by Paul Whitrow, 24th October, 2008 | Permalink
I've been using Javascript for years for various tasks, but in all that time have never had to use a foreach loop (odd huh?). I was rather surprised to discover that Javascript didn't have a direct foreach function akin to PHP's.
So after a little research I came up with this:
var divs = document.getElementsByTagName('DIV');
for( var i in divs)
{
alert(divs[i].tagName);
}
How simple is that?
Ok, so I guess now you're going to want to know how it works...
It's just a for loop that will continue to run as long as there are still elements left in the array (in this case called 'divs'), incrementing the variable 'i' as it goes. The bonus is that you don't need to worry about the length of the array as the loop will stop itself.
So there you have it. Simple, clean and elegant... just like me
I sometimes forget how versatile Javascript can be, and don't use it half as much as I should.

Posted on Friday 24th October, 2008 at 6:46 am by Paul Whitrow, and filed under Development and Javascript
Wanna keep up to date? Subscribe to the site feeds.
Have your say:
NB: Comments are subject to administration.

There are no comments yet for ‘Javascript foreach loop solution’