Home  >  Article  >  Web Front-end  >  JS loop learning: use of while loop statements (detailed examples)

JS loop learning: use of while loop statements (detailed examples)

青灯夜游
青灯夜游Original
2022-08-03 18:04:318385browse

JS loop learning: use of while loop statements (detailed examples)

Looping is to do one thing repeatedly. In the process of writing code, we often encounter some operations that need to be performed repeatedly, such as traversing some data and repeatedly outputting a string. Wait, it would be too troublesome to write line by line. For this kind of repeated operation, we should choose to use a loop to complete it.

The purpose of a loop is to repeatedly execute a certain piece of code. Using loops can reduce programming pressure, avoid code redundancy, improve development efficiency, and facilitate later maintenance. The while loop is the simplest loop statement provided in JavaScript. Let's learn about the use of while loops and do-while loops.

1: while loop

The while loop statement is a when typeloop statement. The loop condition is first judged. When the condition is met, Then execute the loop body and stop when it is not satisfied.

Function: Repeat an operation until the specified condition is not true.

Features: Judge the expression first, and execute the corresponding statement when the expression result is true.

1. JS while loop syntax

while(表达式){    //表达式为循环条件
     // 要执行的代码
}

Statement analysis:

  • First calculate the "expression When the value is true, the "PHP statement block" in the loop body is executed;

    Description: The calculation result of "expression" is of Boolean type (TRUE or FALSE). If Values ​​of other types will also be automatically converted to Boolean values ​​(because PHP is a weak language type and will automatically convert variables into the correct data type based on the value of the variable).

    "Statement block" is a collection of one or more statements surrounded by { }; if there is only one statement in the statement block, you can also omit { }.

  • After the execution is completed, return to the expression and calculate the value of the expression again for judgment. When the expression value is true, continue to execute the "statement block" ...This process will be repeated

  • until the value of the expression is false before jumping out of the loop and executing the statement below while.

The flow chart of the while statement is as follows:

JS loop learning: use of while loop statements (detailed examples)

Usually the "expression" is using comparison The value calculated by the operator or logical operator

The sample code is as follows:

<script>
var i = 1;
while( i <= 5) {
    document.write(i+", ");
    i++;
}
</script>

JS loop learning: use of while loop statements (detailed examples)

##Notes

When writing a loop statement, be sure to ensure that the result of the conditional expression can be false (that is, the Boolean value false), because as long as the result of the expression is true , the loop will continue forever and will not stop automatically. For this kind of loop that cannot automatically stop, we usually call it "infinite loop" or "infinite loop".

If you accidentally create an infinite loop, it may cause the browser or computer to freeze.

If the expression is always true and the loop condition is always true, the while loop will continue to execute and never end, becoming an "infinite loop"

var i = 1;
while(i){
    console.log(i);
}

After running the program, variables will always be output The value of

i until the user forcefully closes it.

JS while loop example

[Example 1] Use while loop to calculate the sum of all integers between 1~100:

<script>
var i = 1;
var sum=0;
while(i<=100){
	sum+=i;
	i++;
}
console.log("1加到100的值为:"+sum);
</script>

Output result:


JS loop learning: use of while loop statements (detailed examples)

[Example 2] Find all leap years between 1900 and 2020, and output them as 6 per line:

<script>
var i = 1900;
var count = 0; //计数闰年的个数
while (i <= 2020) {
    //判断是否是闰年
    if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
        document.write(i + "  ");
        count++;
        if (count % 6 == 0) {
            document.write("<br/>");
        }
    }
    i++;
}
</script>

JS loop learning: use of while loop statements (detailed examples)

2. JS while loop nested structure

while loop can also achieve nesting effect, that is, inside the while loop Nest one or more while loops.

Grammar format:

while(条件1){
     // 条件1成立执行的代码

     while(条件2){
          // 条件2成立执行的代码
           ......
     }
}

Summary: Nesting means inclusion. The so-called while loop nesting is inside a while The way to write a nested while is that the basic syntax of each while is the same as the previous one.

Here, we define the nesting of two while loops. Of course, we can nest as many while loops as we want.

Understand the while loop execution process

After the execution of the inner loop is completed, the conditional judgment of the next outer loop is executed.

JS loop learning: use of while loop statements (detailed examples)

Example 1: Using loop nesting, print counter

<script type="text/javascript">
	var i = 0;
	while(i < 2){
	   console.log("i =", i);
	   var j = 0;
	   while(j < 2){
		console.log("\tj =", j);
		j += 1;
	   }
	   i++;
	}
	console.log("Over");
</script>

JS loop learning: use of while loop statements (detailed examples)

首先,我们定义了一个最外层的 while 循环嵌套,计数器 变量 i 从 0 开始,结束条件是 i

在最外层循环的里面,同时又定义了一个内部循环,计数器变量 j 从 0 开始,结束条件是 i

while循环嵌套总结

JavaScript 的 while 循环也可以实现嵌套的效果,即 while 循环里面嵌套一个或多个 while 循环。

示例2:

<script>
/*
1. 循环打印3次媳妇,我错了
2. 刷碗
3. 上面是一套惩罚,这一套惩罚重复执行3天----一套惩罚要重复执行---放到一个while循环里面
*/
var j = 0
while(j < 3){
    var i = 0
    while(i < 3){
        document.write(&#39;媳妇,我错了<br>&#39;)
        i += 1;
	}
    document.write(&#39;刷碗<br>&#39;)
	document.write(&#39;一套惩罚就结束了!!!!!!!!!!!!<br>&#39;)
    j += 1;
}
</script>

JS loop learning: use of while loop statements (detailed examples)

二:do-while循环

除了while循环,还有一种 do-while 循环。

do-while循环语句是一种“直到型”循环语句,它是先在执行了一次循环体中的“语句块”之后,然后再对循环条件进行判断,如果为真则继续循环,如果为假,则终止循环。

因此:不论表达式的结果,do-while循环语句至少会执行一次“语句块”。

do-while循环语句的特点:先执行循环体,然后判断循环条件是否成立。

1、JS do-while 循环语法

do{
    语句块;  
}while(表达式);//表达式为循环条件

语句解析:

  • 先执行一次循环体中的“语句块”,然后判断“表达式”的值,当“表达式”的值为真时,返回重新执行循环体中的语句块……这个过程会一直重复

  • 直到表达式的值为假时,跳出循环,此时循环结束,执行后面的语句。

说明:

  • 和while循环一样,do-while循环中“表达式”的计算结果一定是布尔型的 TRUE 或 FALSE,如果是其他类型的值也会自动转换为布尔类型的值。

  • do-while语句最后的分号;是无法省略的(一定要有),它是do while循环语法的一部分。

do-while循环语句的流程图如下所示:

JS loop learning: use of while loop statements (detailed examples)

JS do-while 循环示例

【示例1】使用 do-while 输出1~5数字:

<script>
var i = 1;
do {
    document.write(i+", ");
    i++;
}while( i <= 5);
</script>

JS loop learning: use of while loop statements (detailed examples)

【示例2】使用 while 循环计算 1~100 之间所有整数的和:

<script>
var i = 1;
var sum=0;
do{
	sum+=i;
	i++;
}while(i<=100);
console.log("1 + 2 + 3 + ... + 98 + 99 + 100 = "+sum);
</script>

JS loop learning: use of while loop statements (detailed examples)

【示例3】找出 1900 年到 2020 年之间所有的闰年

<script>
var i = 1900;
var count = 0; //计数闰年的个数
do {
    //判断是否是闰年
    if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
		console.log(i);
    }
    i++;
}while (i <= 2020);
</script>

JS loop learning: use of while loop statements (detailed examples)

2、JS do-while 循环嵌套结构

do while循环 也可以实现嵌套的效果,即 do while 循环里面嵌套一个或多个 do while 循环。这种写法就类似于 while 循环 的嵌套。

语法:

do{
    // 语句块1;
    do{
    	// 语句块2;
    	do{
    		// 语句块2;
    		......
	}while(条件3);
    }while(条件2);
}while(条件1);

这里,我们定义了三个 do while 循环的嵌套,当然,我们可以嵌套任意多个的 do while 循环。

案例:使用循环嵌套,打印计数器

<script type="text/javascript">
	var i = 0;
	do{
		console.log("i =", i);
		var j = 0;
		do{
			console.log("\tj =", j);
			j += 1;
		}while(j < 2);
		i++;
	}while(i < 2);
	console.log("Over");
</script>

JS loop learning: use of while loop statements (detailed examples)

首先,我们定义了一个最外层的 do while 循环嵌套,计数器 变量 i 从 0 开始,结束条件是 i

在最外层循环的里面,同时又定义了一个内部循环,计数器变量 j 从 0 开始,结束条件是 i

do while循环嵌套总结

JavaScript 的 do while 循环也可以实现嵌套的效果,即 do while 循环里面嵌套一个或多个 do while 循环。

【推荐学习:javascript高级教程

The above is the detailed content of JS loop learning: use of while loop statements (detailed examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn