Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the JavaScript loop statements and how to use them?

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, I would like to share with you what JavaScript loop sentences have and how to use the relevant knowledge points, the content is detailed, the logic is clear, I believe most people still know too much about this knowledge, so share this article for your reference, I hope you can get something after reading this article, let's take a look at it.

While, for cycle

In programming, it is often necessary to use loop statements to handle all kinds of repetitive work.

For example, to generate a list of student names using JavaScript, you need to create a tag for HTML, and then repeatedly insert child tags into the tag to generate the following HTML structure:

Xiao Ming, Xiao Hong, Xiao Jun.

However, DOM operations are not the main content of this article, which will be covered step by step in subsequent chapters.

There are three types of loop statements: while, do while, and for. You can master all the loops by the end of this article.

While loop syntax

While syntax:

While (exp) {/ / Loop body}

The while statement mainly includes two parts: the execution condition exp and the loop body.

The execution condition is usually a conditional expression, for example, I > 0 means that the loop body is executed only when the variable I is greater than 0.

Take a chestnut:

Let I = 10 while (I > 0) {console.log (I); / / output iMurray in the console;}

The above code creates a variable I with a value of 10, and executes the code in {} when I > 0 is established.

Code console.log (I); you can output a string in the console, knock on the blackboard, and the console knows what it is!

Then execute iMurray, that is, the value of the variable I minus 1.

The purpose of summarizing the above code is to loop the variable I in the browser's console, from 10 to 1.

The result of code execution is as follows:

Cycle condition

In general, the judgment condition of a loop is a conditional expression. The conditional expression returns a Boolean value, executes the loop body when the return value is true, and ends the execution of the loop statement when the return value is false.

In fact, the judgment condition can be any type of expression, and the evaluation result of the expression is also converted to Boolean by implicit conversion.

For example, I > 0 can be abbreviated to while (I):

Let I = 3position while (I) {/ / when I becomes 0, Boolean (I) is false console.log (I); I Murray;}

The above code is true because Boolean (0) is false.

A dangerous endless cycle

The loop condition (variable I) must continue to perform a minus operation, that is, iMurray, in the process of each execution, otherwise the value of I will never be greater than 0, and the loop will never stop, that is, the so-called endless loop.

If there is a dead loop is not without a solution, we can kill the current process to end code execution.

The easiest thing to do is to close the browser and go to the console to kill the browser process.

A dead loop is very dangerous for a program, which can fill up cpu resources, or even the entire memory space, causing a panic.

Therefore, when writing a loop, you must be careful not to forget the change in the loop condition.

A loop with only one line of statements

When there is only one statement in the body of the loop, the {} curly braces can be omitted, simplifying the code.

Take a small plum with a short answer:

Let I = 10 position while (I > 0) console.log (I Murray -)

The execution effect is the same as the above code.

Do {... } while syntax do {/ / loop body} while (exp)

Unlike the while loop, the do {...} while loop swaps the judgment condition with the loop body, and executes the loop body first before judging the loop condition.

Let I = 0 while do {console.log (I); iTunes;} while (i0)

The above code, although I does not meet the execution condition from the beginning, the loop body will still be executed once.

In fact, do {...} while statements are rarely used in real-world programming!

Because there are few circumstances that require us to execute a loop even if the judgment condition is not established.

Even if this happens, we usually use while instead.

For cycle

By comparison, for loop statements are the most complex, but also the most popular.

Syntax for (begin; exp; step) {/ / Loop body}

Interpreting for directly from a grammatical perspective can be confusing. Here is one of the most common cases:

For (let I = 0; I

< 10 ; i++){ console.log(i)} 对比解读: 语法构件对应语句解读beginlet i = 0首次执行循环时,执行一次expi < 10每次循环之前,进行判断,true则执行循环体,否则停止循环stepi++每次循环体执行过后执行 以上代码的执行顺序是: let i = 0;,进入循环语句时执行,只执行一次; 判断i < 10,如果成立继续执行,否则推出循环; 执行console.log(i),控制台输出变量i的值; 执行i++,改变循环变量i的值; 循环执行2 3 4步,直至i < 10不成立。 实际上,以上代码在功能上完全等价于: let i = 0;while(i < 10){ console.log(i); i++;}for的条件变量 和while、do {...} while不同的是,for循环的条件变量i是定义在for语句内部的,相当于一个局部变量,或者说是内联变量,这样的变量只能在for循环内部能够使用。 举个例子: for(let i = 0; i < 10; i++){ console.log(i);}console.log(i); //报错,i is not defined. 如下图: 造成这种结果的原因是,i是for的局部变量,当for语句执行完毕后立即被销毁,后面的程序是无法使用的。 提醒:如果你执行以上代码并没有出现错误,很有可能是在for语句之前就定义了变量i。 当然,我们也可以不使用局部变量: let i = 0;for(i = 0; i < 10; i++){ console.log(i);}console.log(i);// 10 这样我们就可以在for语句外面使用条件变量了! 语句省略 for语句中的任何部分都是可以省略的。 例如,省略begin语句: let i = 0;for (; i < 10; i++) { // 不再需要 "begin" 语句段 alert( i );} 例如,省略step语句: let i = 0;for (; i < 10;) { alert( i++ );//循环变量的修改在循环体中} 例如,省略循环体: let i = 0;for (; i < 10;alert( i++ )) { //没有循环体}break 正常情况下,循环语句需要等待循环条件不满足(返回false),才会停止循环。 但是我们可以通过break语句提前结束循环,强制退出。 举个例子: while(1){//死循环 let num = prompt('输入一个数字',0); if(num >

9) {alert ('the number is too big');} else if (num < 9) {alert ('the number is too small');} else {alert ('clever, loop ends'); break;// end loop}}

The above code is a game of guessing numbers, and the loop condition is always 1, which means that the loop never ends, but when the number 9 is entered, the loop is forced to end with break.

This form of wireless loop plus break is very common in actual programming scenarios, and it is recommended to write it down in a small notebook.

Continue

Continue can stop a single loop that is currently being executed and start the next loop immediately.

For example:

For (let I = 1 +) {if (I% 7) continue; console.log (I);}

The above code outputs all multiples of 7 within 100. when I% 7 is not 0, that is, I is not a multiple of 7, execute the continue statement, skip the following statement directly, and execute the next loop.

Break/continue tag

In the case of multi-layer loop nesting, there will be such a problem, how to jump out of the whole loop body from multiple loops?

For example:

For (let I = 0; I < 3; iTunes +) {for (let j = 0; j < 3; jacks +) {let input = prompt (`Doneboy (${I}, ${j}) `,'); / / if I want to exit from here and directly execute the alert ('calling')} alert ('calling') break tag

If we need to directly let the program execute alert ('dialing') when the user types 0. What should I do?

This requires the use of tags, with the syntax as follows:

Label:for (...) {... Break label;}

The break label statement can jump out of the loop directly and unconditionally to the label label.

For example:

Outer: for (let I = 0; I < 3; iTunes +) {for (let j = 0; j < 3; jacks +) {let input = prompt (`Value at coords (${I}, ${j})`,''); / / if the user enters 0, the user interrupts and jumps out of both loops. If (input=='0') break outer; / / (*)} alert ('toll')

In the above code, break outer looks up for a tag named outer and jumps out of the current loop.

Therefore, control is transferred directly from (*) to alert ('calling').

Continue tag

We can also use continue label to directly end the current loop and start the next one:

Outer: for (let I = 0; I < 3; iTunes +) {for (let j = 0; j < 3; jacks +) {let input = prompt (`Value at coords (${I}, ${j})`,''); / / if the user enters 0, the user interrupts and jumps out of both loops. If (input=='0') continue outer; / / (*)} alert ('toll')

Continue outer can directly end the outermost loop of multiple loops and start the next loop.

For example, when we type 0 at (0), the program jumps directly to (1) instead of ending the entire loop as break does.

Note:

The label does not jump casually, it must meet certain requirements.

For example:

Break label;label: for (...) {...}

It's just not correct.

Homework after class

Using the console.log () method, use a loop to output the following graph:

*********************

Using double loops, create a matrix of 3X3 and allow users to enter matrix data.

These are all the contents of the article "what are the JavaScript Loop sentences and how to use them?" Thank you for your reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report