This article mainly introduces the information and examples of the for loop in the basic Javascript tutorial. for more information, see if you want to run the same code over and over again, and each time the values are different, it is very convenient to use the loop.
The Code is as follows:
Document. write (cars [0] +"
");
Document. write (cars [1] +"
");
Document. write (cars [2] +"
");
Document. write (cars [3] +"
");
Document. write (cars [4] +"
");
Document. write (cars [5] +"
");
But we write it like this.
The Code is as follows:
For (var I = 0; I {
Document. write (cars [I] +"
");
}
Example: 1-numbers are output.
The Code is as follows:
For (var I = 0; I <= 100; I ++)
{
Document. write (I +"
")
}
For is a pre-test loop that can initialize variables before the loop and define the code to be executed after the loop. Its syntax is as follows:
For (inintialization; expression; psot = loop-expression) statement
The execution process is as follows:
1. Execute the initialization statement
2. judge whether expression is true. If expression is true, continue; otherwise, terminate the entire loop body.
3. Execute the statement code of the loop body.
4. Execute the post-loop-expression code.
5. Return to Step 1
The most common form of a for loop is for (var I = 0; I
It indicates that the loop is executed n times in total, which is very suitable for calculating the number of known cycles.
The Code is as follows:
Var aNumbers = new Array ();
Var sMessage = "you entered: \ n ";
Var iTotal = 0;
Var vUserInput;
Var iArrayIndex = 0;
Do {
VUserInput = prompt ("enter a number, or '0' to exit", "0 ");
ANumbers [iArrayIndex] = vUserInput;
IArrayIndex ++;
ITotal + = Number (vUserInput );
SMessage + = vUserInput + "\ n ";
} While (vUserInput! = 0) // exit the loop body when the input is 0 (default)
SMessage + = "Total:" + iTotal;
Document. getElementById ("xxx"). innerHTML = sMessage;
The above is all about the for Loop in javascript. I hope my friends will like it.