search
HomeWeb Front-endJS TutorialJS loop learning: use of while loop statements (detailed examples)

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

Aug 03, 2022 pm 06:04 PM
javascriptLoop structurewhile loop

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
Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor