Monday, June 8, 2009

foreach loop equivalent in javascript.



foreach loop will be easy to use when there is a need to iterate thro' an array or any other collection.

But javascript is not having this option.

Anyway, we can use below type of for loop for achieving the same result of foreach loop.


var arrItems = ["item1","item2","item3"];

for ( var i in arrItems )
{
alert( arrItems[i] );
}

The above code will alert each item in the array one by one.

More Articles...

3 comments:

JC said...

Nice to know! Peace

Paul said...

This code will spit out all properties of an object. It is useful to use.hasOwnProperty(i) when dealing with objects that inherit from a parent. Trust me, this one line check will save hours of debugging.

Prashanth said...

Dude foreach in javascript is bad should avoid it. Array in javascript is not like other languages, looping the way you have mentioned will spit the all method of the Array. I would recommend people to use like this

foo = [1,32,12,43]

for(var i=0;i<foo.length;i++){
foo[i];
}



Thanks for visiting our blog


twitterrss facebook linkedin YouTube subscribe




Subscribe via email

Enter your email address: