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.
[Related recommendations: javascript video tutorial, web front-end】
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>
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
Grammar:
while(exp){ //循环体}
while
The 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--;}
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:
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--;}
Since Boolean(0)
is false
So the above code is established.
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.
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--);
The execution effect is the same as the above code.
do{ //循环体}while(exp);
and while
loop is that do {...} while
The 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);
The above code will output numbers from 0~9
, and the execution results are as follows:
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);
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(begin; exp; step){ //循环体}
直接从语法角度解释for
可能令人疑惑,下面是一个最常见的案例:
for(let i = 0; i < 10 ; i++){ console.log(i)}
对比解读:
语法构件 | 对应语句 | 解读 |
---|---|---|
begin | let i = 0 | 首次执行循环时,执行一次 |
exp | i < 10 | 每次循环之前,进行判断,true 则执行循环体,否则停止循环 |
step | i++ | 每次循环体执行过后执行 |
以上代码的执行顺序是:
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++;}
和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++ )) { //没有循环体}
正常情况下,循环语句需要等待循环条件不满足(返回false
),才会停止循环。
但是我们可以通过break
语句提前结束循环,强制退出。
举个例子:
while(1){//死循环 let num = prompt('输入一个数字',0); if(num > 9){ alert('数字太大了'); }else if(num < 9){ alert('数字太小了'); }else{ alert('真聪明,循环结束'); break;//结束循环 }}
以上代码是一个猜数字的游戏,循环条件永远是1
,也就是说循环永远不会结束,但是当输入数字9
后,就会使用break
强制结束循环。
这种无线循环加上break
的形式在实际编程场景中非常常见,建议用小本本记下来。
continue
可以停止当前正在执行的单次循环,立即开始下一次循环。
举个例子:
for(let i = 1;i < 100; i++){ if(i % 7)continue; console.log(i);}
以上代码输出100
以内的所有7
的倍数,当i % 7
不为0
,也就是说i
不是7
的倍数的时候,执行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!')
如果我们需要在,用户输入0
时,直接让程序执行alert('Done!')
应该怎么做呢?
这就需要使用标签,语法如下:
label:for(...){ ... break label;}
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!');
上述代码中,break outer 向上寻找名为 outer 的标签并跳出当前循环。
因此,控制权直接从 (*)
转至 alert('Done!')
。
我们还可以使用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!');
continue outer
可以直接结束多重循环的最外层循环,开始下一次循环。
例如当我们在(0,0)
处输入0
,那么程序会直接跳到(1,0)
处,而不是像break
一样直接结束整个循环。
注意:
标签并不是随便跳转的,必须符合一定的要求
例如:
break label;label: for(...){...}
就是不正确的。
console.log()
方法,使用循环输出以下图形:* ** *** **** ***** ******
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!