Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I build a loop in JavaScript? [closed]

How can I build a loop in JavaScript?

like image 601
UnkwnTech Avatar asked Sep 09 '08 14:09

UnkwnTech


Video Answer


2 Answers

For loops

for (i = startValue; i <= endValue; i++) {
    // Before the loop: i is set to startValue
    // After each iteration of the loop: i++ is executed
    // The loop continues as long as i <= endValue is true
}

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) {
    // The loop will continue until myCondition is false
}
like image 162
georgebrock Avatar answered Oct 24 '22 03:10

georgebrock


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);
}
like image 27
minty Avatar answered Oct 24 '22 04:10

minty