If you want to run the same code over and over again and the values are different each time, it's convenient to use loops.
Copy Code code as follows:
document.write (Cars[0] + "<br>");
document.write (Cars[1] + "<br>");
document.write (cars[2] + "<br>");
document.write (Cars[3] + "<br>");
document.write (Cars[4] + "<br>");
document.write (Cars[5] + "<br>");
But that's what we write.
Copy Code code as follows:
for (var i=0; i<cars.length;i++)
{
document.write (cars[i]+ "<br>");
}
Example: Output 1-100 of the number
Copy Code code as follows:
for (var i=0;i <=100;i++)
{
document.write (i+ "<br>")
}
For is the pre-test loop, and can initialize the variable before the loop, and define the code to execute after the loop, with the following syntax
for (inintialization;expression;psot=loop-expression) statement
The process of execution is as follows:
1. Execute initialization statement
2. To determine whether expression is true, if it is to continue, otherwise terminate the entire circulation body.
3. Execute Loop Body Statement code
4. Execute post-loop-expression Code
5. Return to step 2nd operation
The most common form for a For loop is for (var i=0; i<n;i++) {statement}
It means that the loop performs a total of n times, which is ideal for known loop count operations.
Copy Code code 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 ' exit", "0");
Anumbers[iarrayindex] = vuserinput;
iarrayindex++;
Itotal + = number (vuserinput);
Smessage + = vuserinput + "\ n";
}while (vuserinput!= 0)//exit loop body when entered as 0 (default)
Smessage + = "Total:" + itotal;
document.getElementById ("xxx"). Innerhtml=smessage;
The above is all about the For loop in JavaScript, and I hope the little friends like it.