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
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)