The For loop:
General writing:
document.write(Arr[0] + "<br>");
document.write(Arr[1] + "<br>");
document.write(Arr[2] + "<br>");
document.write(Arr[3] + "<br>");
document.write(Arr[4] + "<br>");
document.write(Arr[5] + "<br>");
Copy the code
Use the For loop:
for (var i = 0; i < Arr.length; i++) {
document.write(Arr[i] + "<br>");
}
Copy the code
For loop syntax:
For (statement 1; Statements 2; Statement 3) {executed code block}Copy the code
Execute before statement 1 (code block) begins
Statement 2 defines the conditions under which the loop (block of code) is run
Statement 3 executes after the loop (block of code) has been executed
The instance
for (var i = 0; i < 5; I ++) {document.write(" the number is "+ I + "<br>")}Copy the code
From the above example, you can see:
Statement 1 sets the variable (var I =0) before the loop begins.
Statement 2 defines the condition for the loop to run (I must be less than 5).
Statement 3 increments a value (i++) each time a block of code has been executed.
Practical application:
Sum of odd numbers up to 1.100
var sum = 0; var j = 0; For (var I = 1; i <= 100; I ++) {if (I % 2 == 1) {// odd sum += I; j += 1; Document. The write (" first "+ j +" is an odd number is: "+ I +" < br / > ")}} document. Write (" within 100 odd and as: "+ sum);Copy the code
The sum of even numbers up to 2.100
var sum = 0; var j = 0; Var I = 1; i <= 100; I ++) {if (I % 2 == 1) {// Even sum += I; j += 1; Document. The write (" first "+ j +" is an even number is: "+ I +" < br / > ")}} document. Write (" even and within 100 is: "+ sum);Copy the code
Output all daffodils
A daffodil number is a 3-digit number in which the sum of the three powers of the numbers in each bit equals itself (e.g. 1^3 + 5^3+ 3^3 = 153).
for (var i = 100; i < 1000; i++) { var a = i % 10; Var b = parseInt(((I / 10) % 10)); Var c = parseInt(I / 100); / / best if (a * a * b + c + b * b * * * c = c = I) {document. Write (' daffodil number: + I + '< hr / >'); }}Copy the code
The multiplication table
document.write("<table border='1' cellpadding='0' cellspacing='0'width='900'>"); for (var i = 1; i <= 9; i++) { document.write("<tr>"); for (var j = 1; j <= i; j++) { document.write("<td style='background-color: lemonchiffon; text-align: center; < span style =" max-width: 100%; clear: both; min-height: 1em; } document.write("</tr>"); } document.write("</table>");Copy the code