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
2008-09-09 14:55:34
A:
In addition to for loops, there's also while loops.
Check out w3schools.com for some decent tutorials.
17 of 26
2008-09-09 14:57:07
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
2008-09-09 14:57:59
+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
2008-09-09 15:05:00
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
2008-10-09 02:37:54
The problem with the for-in loops can be avoided if you check with the hasOwnProperty: if(!things.hasOwnProperty(i)) { continue; }
Andreas Grech
2009-03-19 18:36:48
A:
You might also consider optimizing your loop speed; see http://www.robertnyman.com/2008/04/11/javascript-loop-performance/
Ken Penn
2008-10-08 20:04:16