Home > Web Front-end > JS Tutorial > body text

An article on solving JavaScript loops

WBOY
Release: 2022-05-12 18:37:31
forward
2918 people have browsed it

This article brings you relevant knowledge about javascript, which mainly introduces related issues such as while loop, do while loop, for loop, break/continue tag, etc. Let’s take a look at it together I hope it helps everyone.

An article on solving JavaScript loops

[Related recommendations: javascript video tutorial, web front-end

while, for loop

In programming, it is often necessary to use loop statements to handle various repetitive tasks.
For example, use JavaScript to generate a list of student names. This requires creating a HTML<ul> tag, and then repeatedly adding it to the tag. Insert the <li> subtag to generate the following HTML structure:

<ul><li>小明</li><li>小红</li><li>小军</li><li>...</li></ul>
Copy after login

However, DOM manipulation is not the main content of this article. Subsequent chapters will introduce it step by step.

There are three types of loop statements: while, do while and for. You will be able to master all loops after reading this article.

while loop

Grammar

whileGrammar:

while(exp){
	//循环体}
Copy after login

whileThe statements mainly include Execution condition exp, and loop body are two parts.

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

For example:

let i = 10;while(i>0){
	console.log(i);//在控制台输出
	i--;}
Copy after login

The above code creates a variable i and assigns it a value of 10, when i > 0 When is established, execute the code in {}.
Codeconsole.log(i);You can output a string on the console and type on the blackboard. The console will know what it is!
Then execute i--, that is, the value of variable i minus 1.

To summarize, the function of the above code is to loop out the variable i in the browser console, from 10 to 1.

The code execution result is as follows:

Loop condition

Normally, the judgment condition of the loop is a conditional expression. The conditional expression returns a Boolean value. When the return value is true, the loop body is executed. When the return value is false, the execution of the loop statement ends.

In fact, the judgment condition can be any type of expression, and the calculation result of the expression will also be converted to Boolean type through implicit conversion.

For example i > 0 can be abbreviated as while(i):

let i = 3;while (i) { // 当 i 变成 0 时,Boolean(i)为false
  console.log(i);
  i--;}
Copy after login

Since Boolean(0) is falseSo the above code is established.

Dangerous infinite loop

The loop condition (variable i) must be continuously executed and minus one during each execution. Operation, that is, i--, otherwise the value of i will always be greater than 0, and the loop will never stop, which is often said to be Endless loop.

If an infinite loop occurs, there is no solution. We can end code execution by killing the current process.

The simplest way is to close the browser and then go to the console to kill the browser process.

Infinite loop is very dangerous for the program. It will occupy cpu resources or even the entire memory space, causing a crash.

So, when writing a loop, be sure not to forget to change the loop conditions.

Loop with only one line of statements

When there is only one statement in the loop body, you can omit the {} curly braces to simplify the code.

Give me a short answer:

let i = 10;while(i>0)console.log(i--);
Copy after login

The execution effect is the same as the above code.

do {…} while

The difference between syntax

do{
	//循环体}while(exp);
Copy after login

and while loop is that do {...} whileThe loop exchanges the positions of the judgment condition and the loop body. Before judging the loop condition, the loop body will be executed first.

let i = 0;do {
  console.log(i);
  i++;} while (i<10);
Copy after login

The above code will output numbers from 0~9, and the execution results are as follows:

Features of do {…} while

That is to say, using the do {...} while statement, the loop body must be executed at least once:

let i = 0do {
	console.log(i)
	i--;}while(i>0);
Copy after login

The above code, although i If the execution conditions are not met at the beginning, the loop body will still be executed once.

实际上,do {...} while语句在现实编程过程中使用的非常少!
因为很少有情况需要我们在判断条件不成立的情况下,依旧要执行一次循环体。
即使存在这种情况,我们也通常使用while代替。

for 循环

相较而言,for循环语句是最复杂的,但也是最受欢迎的。

语法

for(begin; exp; step){
	//循环体}
Copy after login

直接从语法角度解释for可能令人疑惑,下面是一个最常见的案例:

for(let i = 0; i < 10 ; i++){
	console.log(i)}
Copy after login

对比解读:

语法构件对应语句解读
beginlet i = 0首次执行循环时,执行一次
expi < 10每次循环之前,进行判断,true则执行循环体,否则停止循环
stepi++每次循环体执行过后执行

以上代码的执行顺序是:

    <li>let i = 0;,进入循环语句时执行,只执行一次;<li>判断i < 10,如果成立继续执行,否则推出循环;<li>执行console.log(i),控制台输出变量i的值;<li>执行i++,改变循环变量i的值;<li>循环执行2 3 4步,直至i < 10不成立。

实际上,以上代码在功能上完全等价于:

let i = 0;while(i < 10){
	console.log(i);
	i++;}
Copy after login

for的条件变量

whiledo {...} while不同的是,for循环的条件变量i是定义在for语句内部的,相当于一个局部变量,或者说是内联变量,这样的变量只能在for循环内部能够使用。

举个例子:

for(let i = 0; i < 10; i++){
	console.log(i);}console.log(i); //报错,i is not defined.
Copy after login

如下图:

造成这种结果的原因是,ifor的局部变量,当for语句执行完毕后立即被销毁,后面的程序是无法使用的。

提醒:如果你执行以上代码并没有出现错误,很有可能是在for语句之前就定义了变量i

当然,我们也可以不使用局部变量:

let i = 0;for(i = 0; i < 10; i++){
	console.log(i);}console.log(i);// 10
Copy after login

这样我们就可以在for语句外面使用条件变量了!

语句省略

for语句中的任何部分都是可以省略的。

例如,省略begin语句:

let i = 0;for (; i < 10; i++) { // 不再需要 "begin" 语句段
  alert( i );}
Copy after login

例如,省略step语句:

let i = 0;for (; i < 10;) {
  alert( i++ );//循环变量的修改在循环体中}
Copy after login

例如,省略循环体:

let i = 0;for (; i < 10;alert( i++ )) {
	//没有循环体}
Copy after login

break

正常情况下,循环语句需要等待循环条件不满足(返回false),才会停止循环。

但是我们可以通过break语句提前结束循环,强制退出。

举个例子:

while(1){//死循环
	let num = prompt(&#39;输入一个数字&#39;,0);
	if(num > 9){
		alert('数字太大了');
	}else if(num < 9){
		alert('数字太小了');
	}else{
		alert('真聪明,循环结束');
		break;//结束循环
	}}
Copy after login

以上代码是一个猜数字的游戏,循环条件永远是1,也就是说循环永远不会结束,但是当输入数字9后,就会使用break强制结束循环。

这种无线循环加上break的形式在实际编程场景中非常常见,建议用小本本记下来。

continue

continue可以停止当前正在执行的单次循环,立即开始下一次循环。

举个例子:

for(let i = 1;i < 100; i++){
	if(i % 7)continue;
	console.log(i);}
Copy after login

以上代码输出100以内的所有7的倍数,当i % 7不为0,也就是说i不是7的倍数的时候,执行continue语句,直接跳过后面的语句,执行下一次循环。

break/continue标签

在多层循环嵌套的情况下,会有这样一个问题,怎样从多重循环中跳出整个循环体呢?

例如:

for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    let input = prompt(`Value at coords (${i},${j})`, '');
    // 如果我想从这里退出并直接执行 alert('Done!')
  }}alert('Done!')
Copy after login

break标签

如果我们需要在,用户输入0时,直接让程序执行alert('Done!')应该怎么做呢?

这就需要使用标签,语法如下:

label:for(...){
	...
	break label;}
Copy after login

break label语句可以直接无条件的跳出循环到标签label处。

例如:

outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    let input = prompt(`Value at coords (${i},${j})`, '');
    // 如果用户输入0,则中断并跳出这两个循环。
    if (input=='0') break outer; // (*)
  }}alert('Done!');
Copy after login

上述代码中,break outer 向上寻找名为 outer 的标签并跳出当前循环。

因此,控制权直接从 (*) 转至 alert('Done!')

continue标签

我们还可以使用continue label直接结束当前循环,开始下次循环:

outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    let input = prompt(`Value at coords (${i},${j})`, '');
    // 如果用户输入0,则中断并跳出这两个循环。
    if (input=='0') continue outer; // (*)
  }}alert('Done!');
Copy after login

continue outer可以直接结束多重循环的最外层循环,开始下一次循环。

例如当我们在(0,0)处输入0,那么程序会直接跳到(1,0)处,而不是像break一样直接结束整个循环。

注意:
标签并不是随便跳转的,必须符合一定的要求

例如:

break label;label: for(...){...}
Copy after login

就是不正确的。

课后作业

    <li>利用console.log()方法,使用循环输出以下图形:
*
**
***
****
*****
******
Copy after login
    <li>利用双重循环,创建一个3X3的矩阵,并让用户可以输入矩阵数据。

【相关推荐:javascript视频教程web前端

The above is the detailed content of An article on solving JavaScript loops. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template