Characteristics of a for loop
There are two common types of loops, the for loop and the while loop. The while loop is usually faster than the for loop, but the code for is simpler than the while loop!
The running flow of the for loop
Common for loop constructs:
for(var i=0; i<100; i++){/* var i=0; Is to define the initial variable. i<100; It's a cyclic condition. I++; Is the variable */
console.log(i)/* Loop statement */
}
Copy the code
For (define the initial variable ①; Cyclic conditions ②; Variable change value ④) {
Loop statement; 3.
}
Execution order: ①②③④ ②③④②③ ③④…… Until I don’t
① Define initial variables: execute semicolons in parentheses only once before entering the loop
② Cycle conditions: each time into the cycle will execute and judge **
④ Variable change value: each time the loop is completed, ③ the content executed after the loop statement
(1) and (4) If there are multiple statements, can use a comma to open loop condition if there are multiple cannot use a comma, can only use logic and && or logic or | | when there is no condition, directly into blocks by default, ### break demo javascript for(var I =0; i<10; i++){ if(i===5){ break; } } console.log(i);Copy the code
Break result:
Break means to jump out of the loop and not execute the loop again
Contine demo:
for(var i=0; i<10; i++){if(i===5) {continue; }}console.log(i);
Copy the code
Contine’s jump results:
Contine is breaking out of a single loop of I ===5, the whole loop will continue!
The for loop is nested with the for loop
1. Multiplication table
str="<table>";/* Set a table */
for(var row=1; row<=9; row++){/* row is the initial vertical row. If it is less than or equal to 9, it increments by 1 */ each time
str+="<tr>";
for(var col=1; col<=row; col++){/* The cell starts at 1, increments by 1 each time the row increases, and the increment of COL increases by one cell per column */
str+="<td>"+col+"*"+row+"="+col*row+"</td>";
}
str+="</tr>";
}
str+="</table>";
document.write(str);
Copy the code
2. Isosceles triangle
var str="";
for(var i=1; i<10; i++){/* I starts at 1 and is less than 10. Each loop increments by 1 and loops 9 times */
str+="<br>"/* the for statement completes once, and the second time starts br newline */
for(var m=10; m>i; m--){/* m decrement by 1 each loop has one less space than the last loop * /
str+=" "
}
for(var j=0; j<i; j++){/* Loop print * and Spaces , j cannot exceed the size of I. Each loop has one more * and space */ than the last one
str+="* "}}document.write(str);
Copy the code
3. Sum of prime numbers
for(var x=0,i=2; i<100; i++){/* Define an x for the sum, I less than 100 increments by 1 */
for(var z=true,y=2; y<i; y++){/* Define a z as true, y less than I, and y increments by 1 */ each time through the loop
if(i%y===0) {/* Determine if I is divisible by y */
z=false;/* If divisible, it is not prime. Change the Boolean value to false */}}if(z){
x+=i;/* Prime numbers add to x */}}document.write(x);
Copy the code