javascript loop(3)

Loop statement in js

  • for loop
  • while loop
  • do while loop

What is loop

 在程序中,反复被执行的语句叫做循环体,循环体是否能被重复执行,取决于循环的终止条件,由循环体及循环的终止条件组成的语句叫做循环语句

The purpose of the loop

Some code can be executed repeatedly

for loop

Purpose: Some codes can be executed repeatedly, usually related to counting.

grammar

    for(初始化变量;条件表达式;操作表达式) {
        //循环体
    }

  • Initialization variable: usually used to count, use var to declare
  • Conditional expression: depends on the termination condition of the loop body
  • Operation expression: used to update the initialization variable

The execution process of the for loop


    <script>
        for (var i = 1; i <= 100; i++) {
            //在控制台打印100遍的"hello 尧子陌"
            console.log("hello 尧子陌")
        }
    </script>

Insert picture description here

Principle of execution

i = 1 只会被执行一次,执行完毕后,执行条件表达式,若满足,则执行循环体的语句,若不满足,则跳出循环体。然后执行条件表达式自增变量,判断条件表达式是否满足,若满足,则执行循环体的语句,若不满足,则跳出循环体

Breakpoint debugging of for loop

Set a breakpoint on a certain line of the program to better observe how the program is running

Proceed as follows

  • Press the f12 key to enter sources (root source), set a breakpoint operation on the current line where a breakpoint needs to be set, and refresh the browser
  • Press the up and down arrows to proceed to the next step

Observe the changes in the value of variables better through watch

Insert picture description here

Control the number of loops through variables

In js, you can control the number of loops by converting the value entered by prompt into an integer

    <script>
        /* 
                *1.弹出一个输入框,用户输入值,把这个数值保存成变量
                2.通过变量名来控制循环的次数
                
                 */

        var userName = parseInt(prompt("请输入任意正整数"));

        for (var i = 1; i <= userName; i++) {
            console.log('Hello')
        }
    </script>

Insert picture description here

Different codes can be executed through a for loop

Enter a person 1 year old and 100 years old, and prompt birth and death


    <script>
        for (var i = 1; i <= 100; i++) {
            if (i == 1) {
                console.log('今年一岁了,你出生了')
            } else if (i == 100) {
                console.log('今年100岁了,你已经死亡了')
            } else {
                console.log('今年' + i + '岁了')
            }
        }
    </script>

Insert picture description here

The for loop can perform the same operation

Find the cumulative sum of 1~100


    <script>
        //求1~100之间累加的和

        var sum = 0;
        for (var i = 1; i <= 100; i++) {
            sum += i;
        }
        console.log('sum最终的值', sum); //5050
    </script>

Insert picture description here

The idea is as follows

  • To loop 100 times, a counter i is needed
  • Need a value to store the result as sum
  • Calculation formula: sum=sum+i

for loop to average

Find the average between 1 and 100


  <script>
        //需要声明一个求和的变量及求平均数的变量
        var sum = 0,
            average = 0

        for (var i = 0; i <= 100; i++) {
            sum += i;
        }
        // 平均值为
        var average = sum / 100;
        console.log('1~100之间的平均数:' + average) //50.5
    </script>
</head>



Insert picture description here

The for loop finds the sum of all odd and even numbers from 1 to 100.

The idea is as follows: How to judge a number as an even number?

Solution: Divisible by 2 and the remainder is 0, it is an even number, otherwise it is an odd number.


    <script>
        //需要声明一个偶数及奇数的变量
        var even = 0,
            odd = 0;

        for (var i = 0; i <= 100; i++) {
            if (i % 2 == 0) {
                even += i;
            } else {
                odd += i;
            }
        }
        console.log('1~100之间所有偶数的和:', even)
        console.log('1~100之间所有奇数的和:', odd)
    </script>



Insert picture description here

The for loop finds the sum within 100 that is divisible by 3

    <script>
        //需要声明一个变量来保存能被3整出的和的结果
        var result = 0;
        for (var i = 1; i <= 100; i++) {
            if (i % 3 == 0) {
                result += i
            }
        }

        console.log('1~100之间能被3整除的和:', result)
    </script>
</head>

Insert picture description here

Student case of for loop

Pop up the input box, enter the total number of class, find the total score and average score sum


analysis

1. The input box pops up, and the user enters the total number of people in the class (userName)

2. Enter the student's grades one by one (stored as sorce), you need to use a for loop, the number of pop-up input boxes is related to the total number of students in the class. Conditional expression i<=userName

3. The internal processing of the program, calculate the total score (sum), and then calculate the average (average)



    <script>
        //要求:计算学生的总成绩及平均数
        var userName = Number(prompt("输入班级的总人数"));
        var sum = 0;
        var average = 0;
      

        for (var i = 1; i <= userName; i++) {
            var sorce = Number(prompt('请输入第' + i + "个学生成绩"));

            sum += sorce;
        }

        //学生的总成绩
        console.log("班级的总成绩", sum);
        //学生的平均成绩
        var average = sum / userName;
        console.log('班级的平均成绩:', average)
    </script>


Insert picture description here

for loop printing n planets and stars

analysis

1. Control the number of stars by the value entered by prompt
2. Print the stars on the console by appending a string

  <script>
        var userName = prompt('请输入星星的个数');

        var str = "" //声明一个变量来存储空字符串
        for (var i = 1; i <= userName; i++) {
            str += "★";
         
        };
        console.log(str)
    </script>

Insert picture description here

Double for loop of for loop

Nesting a for loop on the basis of a for loop is called a double for loop

grammar


for(外循环初始化变量;外循环条件表达式;外循环操作表达式) {
    for(内循环初始化变量;内循环条件表达式,内循环操作表达式) {
           //执行的语句
    }
    
}

Precautions

  • The inner loop can be regarded as the statement of the outer loop
  • The outer loop executes once, the inner loop executes all

    <script>
        //外层循环
        for (var i = 1; i <= 3; i++) {

            console.log('外层循环执行的:' + i + '次')
            for (var j = 1; j <= 3; j++) {
                console.log('内层循环执行的:' + j + '次')
            }
        }
    </script>


Insert picture description here

Double for loop printing 5 rows and 5 columns of stars


<script>
    var str = '';
    for (var i = 0; i <= 5; i++) {
        for (var j = 0; j <= 5; j++) {
            str += '★'
        };
        str += '\n'
    }

    console.log(str);
</script>

Insert picture description here

Double for loop input N rows and N columns of stars


<script>
    //控制行数
    var rows = Number(prompt('请输入需要的行数'));

    //控制列数
    var cols = Number(prompt('请输入需要的列数'));

    //声明一个空字符串
    var str = ''

    //双重for循环

    for (var i = 0; i < rows; i++) {
        for (var j = 0; j < cols; j++) {
            str += '★'
        };
        str += '\n'
    };
    console.log(str);
</script>


Insert picture description here

Double for loop printing inverted triangle

Core idea: j= i; j<10; j++


<script>
    var str = '';

    for (var i = 0; i < 10; i++) {
        for (var j = i; j < 10; j++) {
            str += '★'
        };
        str += '\n'

    }
    console.log(str);
</script>

Insert picture description here

Double for loop printing regular triangle

Core idea: j=0;j<i;j++


<script>
    var str = '';
    for (var i = 0; i < 10; i++) {
        for (var j = 0; j < i; j++) {
            str += '*'
        };
        str += '\n'
    }
    console.log(str);
</script>

Insert picture description here

Double for loop printing ninety-nine multiplication table

<script>
    var str = '';
    for (var i = 1; i <= 9; i++) {
        for (j = 1; j <= i; j++) {
            str += j + '*' + i + '=' + i * j + '\t'
        };

        str += '\n'

    }
    console.log(str);
</script>

Insert picture description here

Summary of for loop

  • The for loop can repeatedly execute some of the same code
  • The for loop can execute different codes
  • Double for loop, the outer loop is executed once, and the inner loop is executed all.

while loop

grammar

while(条件表达式) {
    //循环体代码
    操作表达式
    
}

Precautions

  • If the conditional expression in the while loop is true, the statement in the loop body is executed, otherwise it is false, the statement in the loop body is not executed
  • After executing the statement in the loop body, the operation expression will be incremented, and it will continue to determine whether the conditional expression is satisfied (the above steps)
  • The while loop can judge more complicated conditions.

Print hello word in while loop

<script>
    var i = 1;
    while (i <= 100) {
        console.log('hello word');
        i++
    };
</script>

Insert picture description here

The while loop prints the life of a person and prompts birth and death


<script>
    var i = 1;
    while (i <= 100) {
        if (i === 1) {
            console.log('出生了');
        } else if (i === 100) {
            console.log('死亡了');
        } else {
            console.log('你已经' + i + '岁');
        };
        i++
    }
</script>

Insert picture description here

Calculate the sum of all integers from 1 to 100 in the while loop


<script>
    var i = 1;
    var sum = 0;
    while (i <= 100) {
        sum += i;
        i++
    }
    console.log('1~100之间所有整数的和:', sum);
</script>

Insert picture description here

Conditional judgment of while loop (Do you love me)

Requirement: The input box pops up, and the user enters I love you, then stop asking, otherwise it keeps asking infinitely.

<script>
    var username = prompt('你爱我吗');
    while (username !== '我爱你') {
        username = prompt('你爱我吗');
    }
    alert('我也爱你  小宝贝')
</script>


Insert picture description here

do while loop

     The do while loop is a variant of the while loop. The do while loop will execute the code of the loop body at least once, and then the operation expression will be incremented or decremented, and then the conditional expression will be judged. If it is true, the loop body will be executed. Statement, false is not executed

var i =1;
do {
    //循环体语句
    操作表达式
}while(条件表达式)

The do while loop prints the life of a person and prompts birth and death

<script>
    var i = 1;
    do {
        if (i === 1) {
            console.log('恭喜你 你出生了');
        } else if (i === 100) {
            console.log('恭喜你  你死亡了');
        } else {
            console.log('你已经' + i + '岁');
        }
        i++
    } while (i <= 100)
</script>

Insert picture description here

The do while loop prints the sum of all integers between 1 and 100


<script>
    var i = 1;
    var sum = 0;
    do {
        sum += i;
        i++
    } while (i <= 100);
    console.log('1~100的整数的值:', sum);
</script>

Insert picture description here

Conditional judgment of do while loop (Do you love me)

Requirement: The input box pops up and displays "Do you love me?" If the user enters I love you, the prompt will stop asking, otherwise it will keep asking.

<script>
    do {
        var username = prompt('你爱我吗')
    } while (username !== '我爱你')

    alert('我也爱你  宝贝')
</script>

Insert picture description here

Summary of the cycle

  • The loop in JS: for loop while loop di while loop
  • Under special circumstances, the three can be substituted for each other
  • do while is a variant of while. The difference from while is that the execution order is different. The while loop is first judged and then executed, and the do while loop is executed at least once.
  • Focus on the for loop

The difference between continue break

continue

continue: Jump out of this loop and proceed to the next loop

Find the sum of all numbers from 1 to 100 that can be divisible by 7

<script>
    var sum = 0;
    for (var i = 1; i <= 100; i++) {
        if (i % 7 === 0) {
            continue
        }
        sum += i;
    }
    console.log(sum);
</script>

Insert picture description here

break

Jump out of the entire loop immediately, and no longer do the next loop

When i is equal to 3, jump out of the entire loop

<script>
    for (var i = 0; i < 5; i++) {
        if (i === 3) {
            break
        }
        console.log(i);
    }

</script>


Insert picture description here

Simple ATM machine

Insert picture description here
Use the simplest switch statement


    <script>
        //简易ATM机
        var corpus = 100; //本金

        var userName = Number(prompt('请输入你要的操作\n1.存钱\n2.取钱\n3.显示余额\n4.退出'))


        switch (userName) {
            case 1:
                var depvar = Number(prompt("请问需要存多少钱?"));
                corpus = corpus + depvar;
                alert('余额为' + corpus)
                break;
            case 2:
                var taken = Number(prompt("请问需要取多少钱?"));
                if (taken > corpus) {
                    alert('余额不足')
                } else if (taken < corpus) {
                    corpus = corpus - taken;
                    alert('余额为' + corpus)
                }
                break;
            case 3:
                alert(corpus);
                break
            case 4:
                if (userName == 4) {
                    alert('退出成功')
                }
                break
            default:
                alert("输入错误");
                break;


        }
    </script>




Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45419127/article/details/111473451