If you want to run the same code over and over again, and the values are different each time, it is convenient to use loops.
document.write (Cars[0] + "<br>");d ocument.write (cars[1] + "<br>");d Ocument.write (cars[ 2] + "<br>");d ocument.write (cars[3] + "<br>");d ocument.write (cars[4] + "<br > ");d ocument.write (cars[5] +" <br> ");
But we write this.
for (var i=0; i<cars.length;i++) {document.write (Cars[i]+ "<br>");}
Example: Output 1-100 number
for (var i=0;i <=100;i++) {document.write (i+ "<br>")}
For is a pre-test loop, and you 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 following procedures are performed:
1. Execute initialization statement
2. Determine if expression is true and if yes, continue, or terminate the entire loop body.
3. Executing the Loop Body statement code
4. Execute post-loop-expression Code
5. Return to the 2nd step operation
The most common form for a For loop is for (var i=0; i<n;i++) {statement}
It indicates that the loop executes a total of n times and is well suited for known loop count operations.
JavaScript Basic Series (vi) loop statement (for Loop)