Download presentation
Presentation is loading. Please wait.
1
Loops Kevin Harville
2
for loops Loop, through the braced code starting with myVar at 1.
for (myVar = 1; myVar<=10; myVar + 2){ alert(myVar) } Loop, through the braced code starting with myVar at 1. Continue as long as myVar is <= 10 Increment by 2
3
while loops while (condition == true){ alert("True");
//maybe the condition changes } While loops repeat as long as the condition remains true.
4
while loops //previous statements … while (condition == true){
alert("True"); } //subsequent statements… The loop would be passed over if the condition were never true--Just like an if statement.
5
do while loops do { alert("True") //maybe the condition changes
} while (condition == true); When the program reaches this point, the loop would execute at least once. The condition is at the end of the loop.
6
Breaking out while (condition == true){ alert("True");
if (tired == true) break; } //subsequent lines While loops repeat as long as the condition remains true….unless we break out of the loop. For loops repeat their iterations* as scheduled until a break is reached. *Iteration: Geekspeak for times.
7
continue var x = 5; while (x < 10) { x++; if (x == 7) continue;
document.write(x + "<BR>"); } Continue continues on with the next iteration of the loop.
8
for … in loops Similar to the previous but cycle through all properties of an object. Know they exist. They are handy, particularly for debugging. for (i in document) { document.write("<p>" + i ="<br>"); document.write(document[i]); }
9
Loops and Arrays Loops are very often used with arrays.
Remember, arrays are objects that consist of several subscripted variables: myArray = new Array(); myArray[0] = 24 myArray[1]= 12 myArray[2] = 4
10
Looping through an Array
for (i=0; i <= 2; i++) { alert(myArray[i]) }
11
Putting it all together:
myArray = new Array(); myArray[0] = 24 myArray[1]= 12 myArray[2] = 4 for (i=0; i <= 2; i++) { alert(myArray[i]) }
12
Summary of Loops for loop while loop do / while loop
for / in loop for use with object properties break finishes the loop altogether continue goes directly to the next iteration Much can be accomplished with arrays and loops
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.