SMF For Free Support Forum

General Stuff => Programming => JavaScript => Topic started by: slayer766 on February 04, 2008, 07:30:12 pm

Title: A better understanding of for loops
Post by: slayer766 on February 04, 2008, 07:30:12 pm
For loops basically loop through something you specify and will execute forever until you either input a break, an if condition, or simply tell the loop to end at a certain number. Here are some examples of the three I said:

Example 1: Breaking a for loop with break.

Breaks can be used in functions, loops, etc. I will show you how to use the break in a for loop.
Code: [Select]
<script type="text/javascript">
for(i = 0; i < 5; i++){
document.write(i);
break;
}
</script>

That will basically stop the loop at 0, because it breaks the code after it writes 0. Breaks are quite effective to haulting something.


Example 2: Stopping a for loop with an if condition.

An if condition will just basically stop the loop once it reaches X amount.
Code: [Select]
<script type="text/javascript">
for(i = 0; i < 5; i++){
if(i == 3){
document.write(i);
}
}
</script>

That will count all the way up to 3 and then write the number 3 and go no further than that.


Example 3: Completeing a for loop with a specified number
Code: [Select]
<script type="text/javascript">
for(i = 0; i < 5; i++){
document.write(i);
}
</script>
It's as simple as that. The loop will count up to 5, which it will become 4 because the loop started on 0.