preface

Loop statements: A loop statement executes a piece of code multiple times.

The for loop

Syntax for the for loop

Grammar:

For (1) initialize the expression; ② Conditional expression; ④ update expression){③ statement... }Copy the code

Execution process:

(1) Execute the initialization expression, initialize the variable (the initialization expression will only be executed once) (2) execute the conditional expression, determine whether to execute the loop: if true, execute the loop; if false, terminate the loop; (4) execute the update expression, and continue to repeat the update expression after execution (2)Copy the code

For loop example:

	for (var i = 1; i <= 100; i++) {
		console.log(i);
	}
Copy the code

Explanation of the above code:

For loop example

	for (var i = 1; i < 13; i = i + 4) {
		console.log(i);
	}

Copy the code

The traversal steps of the code above:

Var I = 1; This statement, so the value of I is 1. The program then verifies that I <13 is true and that 1<13 is true, so execute the body of the loop once. After the body of the loop is executed, I = I +4 is executed, so the value of I is 5. The program will verify that I <13 is true, and that 5<13 is true, so execute the body of the loop once. After the body of the loop is executed, I = I +4 is executed, so the value of I is 9. The program will verify that I <13 is true, and that 9<13 is true, so execute the body of the loop once. After the body of the loop is executed, the statement I = I +4 is executed, so the value of I is 13. It's going to verify that I <13, 13<13 is false, so it's not going to execute the loop, it's going to exit the loop. Final output The output is 1, 5, and 9Copy the code

Let’s do a couple of problems.

Title 1:

	for (var i = 1; i < 10; i = i + 3) {
		i = i + 1;
		console.log(i);
	}
Copy the code

Output results: 2, 6, 10

Topic 2:

	for (var i = 1; i <= 10; i++) {

	}
	console.log(i);
Copy the code

The command output is 11

Title 3:

	for(var i = 1; i < 7; i = i + 3){

	}
	console.log(i);
Copy the code

Output: 7

Topic 4:

	for (var i = 1; i > 0; i++) {
		console.log(i);
	}
Copy the code

Infinite loop.

While loop statement

The while loop

Grammar:

while(conditional expression){statement... }Copy the code

Execution process:

The while statement evaluates the conditional expression: if true, the loop body is executed: after the loop body is executed, the expression continues to evaluate; if true, the loop body is executed; and so on, if false, the loop is terminatedCopy the code

If necessary, we can use break to terminate the loop.

do… The while loop

Grammar:

	do{statement... }while(Conditional expression)Copy the code

Execution process:

do... When executing a while statement, the body of the loop is executed first: after the body of the loop is executed, the conditional expression after the while is judged: if the result is true, the body of the loop continues to be executed, and so on if the result is false, the loop is terminatedCopy the code

While loops and do… While loop

The function of these two statements is similar except that:

  • While is to judge and then execute, while do… While is execute and judge later.

That is to say, do… While guarantees that the body of the loop executes at least once, while does not.

While loop example

Question: How many years does it take to grow from $1,000 to $5,000 if the annual interest rate on the investment is 5%?

Code implementation:

<! DOCTYPEhtml>
<html lang="">

<head>
    <meta>
    <meta>
    <meta>
    <title>Document</title>
</head>

<body>
    <script>
        /* * How many years does it take to grow from 1000 to 5000 if the annual interest rate of investment is 5% * * 1000 1000*1.05 * 1050 1050*1.05 */

        // Define a variable that represents the current amount of money
        var money = 1000;

        // Define a counter
        var count = 0;

        // Define a while loop to calculate the amount of money per year
        while (money < 5000) {
            money *= 1.05;

            // Make count increment
            count++;
        }

        console.log(money);
        console.log("All we need." + count + "Year");

    </script>
</body>

</html>


Copy the code

Print result:

5003.18854203379 takes 33 years altogetherCopy the code

In addition, you can also do the math yourself. If the investment has an annual interest rate of 5%, it will take 48 years to grow from $1,000 to $10,000:

10401.269646942128 takes 48 yearsCopy the code

Break and continue

This is a very important point.

break

  • Break can be used to exit the switch statement or the entire loop (loop statements include for, while). Not including if. Do not use break or continue in if; otherwise, an error will be reported.

  • Break immediately terminates the nearest loop statement.

  • You can create a label for the loop statement to identify the current loop (format: label: loop statement). When you use the break statement, you can follow the break with a label so that the break will end the specified loop, not the nearest one.

Example 1: Terminate a loop statement with break

    for (var i = 0; i < 5; i++) {
        console.log('I value: + i);
        if (i == 2) {
            break;  // Notice that the break is used in the if, but the break is for the outside for loop.}}Copy the code

Print result:

Value of I :0 value of I :1 Value of I :2Copy the code

Example 2: Using label

    outer:
    for (var i = 0; i < 5; i++) {
        console.log("Value of outer loop I:" + i)
        for (var j = 0; j < 5; j++) {
            break outer; // Jump out of the outer loop where outer is located (this is my custom label)
            console.log("Value of inner circulation j :"+ j); }}Copy the code

Print result:

The value of outer loop I: 0Copy the code

continue

  • Continue can be used to skip the next loop.

  • Also, continue by default only works on the loop closest to it.

All kinds of practice

Exercise 1: Prime correlation

Title: Receive a user input number in the page and determine whether the number is prime.

Code implementation:

<! DOCTYPEhtml>
<html>

<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript">
        /* Prime: A number that is divisible only by 1 and itself. 1 is neither prime nor composite. A prime must be a natural number greater than 1. * /

        var num = prompt("Please enter an integer greater than 1 :");

        // Check whether the value is valid
        if (num <= 1) {
            alert("This value is illegal!");
        } else {

            // Use the flag bit to save the current status of the number
            // The current num is prime by default
            var flag = true;

            // check whether num is prime
            // Get the number between 2 and num
            for (var i = 2; i < num; i++) {
                //console.log(i);
                // Determine whether num is divisible by I
                if (num % i == 0) {
                    // If num is divisible by I, num must not be prime
                    // Set flag to false
                    flag = false; }}// If num is prime, output
            if (flag) {
                alert(num + "Prime number!!");
            } else {
                alert("This is not prime.")}}</script>
</head>

<body>
</body>

</html>

Copy the code

Exercise two: Prime correlation

Title: Print all primes between 1 and 100

Code implementation:

<! DOCTYPEhtml>
<html>

<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript">

        /* * Prints out all primes between 1 and 100 */

        // Print all numbers between 2 and 100
        for (var i = 2; i <= 100; i++) {

            // Create a Boolean value to store the result. Default I is prime
            var flag = true;

            // Check if I is prime
            // Get all numbers between 2 and I
            for (var j = 2; j < i; j++) {

                // Determine if I is divisible by j
                if (i % j == 0) {
                    // If I is not prime, change flag to false
                    flag = false; }}// If it is prime, print the value of I
            if (flag) {
                console.log(i); }}</script>
</head>

<body>
</body>

</html>

Copy the code

Print result:

Exercise three: 99 times table

Code implementation:

<! DOCTYPEhtml>
<html>

<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        body {
            width: 2000px;
        }

        span {
            display: inline-block;
            width: 80px;
        }
    </style>
    <script type="text/javascript">

        / * * 1. Print 99 multiplication table 1 = 1 * 1 * 1 * 2 * 2 = 2 * 2 = 4 * 1 2 * 3 * 3 = 3 = 3 * 3 = 6 to 9 * 1 * 4 = 4 and 2 * 4 = 8 3 * 4 * 4 = 16 * 4 = 12... 9*9=81 * * 2. Print out all prime numbers */ between 1 and 100

        // Create an outer loop to control the height of the multiplication table
        for (var i = 1; i <= 9; i++) {
            // Create an inner loop to control the width of the graph
            for (var j = 1; j <= i; j++) {
                document.write("<span>" + j + "*" + i + "=" + i * j + "</span>");
            }

            // Outputs a newline
            document.write("<br />");
        }
    </script>
</head>

<body>
</body>

</html>
Copy the code

Page effect: