views:

902

answers:

5

How can I build a loop in JavaScript?

A: 

A loop in JavaScript looks like this:

for (var=startvalue;var<=endvalue;var=var+increment) 
{
    code to be executed
}
Unkwntech
A: 

In addition to for loops, there's also while loops.

Check out w3schools.com for some decent tutorials.

17 of 26
A: 

Here is an example of a for loop:

We have an array of items nodes.

for(var i = 0; i< nodes.length; i++){
    var node = nodes[i];
    alert(node);
}
minty
+17  A: 

For loops

for(i = startValue; i <= endValue; i++)
{
    // Your code here
}

For...in loops

for( i in things )
{
    // If things is an array, i will usually contain the array keys *not advised*
    // If things is an object, i will contain the member names
    // Either way, access values using: things[i]
}

It is bad practice to use for...in loops to itterate over arrays. It goes against the ECMA 262 standard and can cause problems when non-standard attributes or methods are added to the Array object, e.g. by Prototype. (Thanks to Chase Seibert for pointing this out in the comments)

While loops

while( myCondition )
{
    // Your code here
    // When you're finished, set myCondition to false
}
georgebrock
You should not use for...in to loop over arrays. This will cause problems with Prototype. See http://www.prototypejs.org/api/array
Chase Seibert
The problem with the for-in loops can be avoided if you check with the hasOwnProperty: if(!things.hasOwnProperty(i)) { continue; }
Andreas Grech
A: 

You might also consider optimizing your loop speed; see http://www.robertnyman.com/2008/04/11/javascript-loop-performance/

Ken Penn