Article directory
while, for loop
In programming, it is often necessary to use loop statements to handle various repetitive tasks.
For example, using JavaScript
to generate a list of student names requires creating a HTML
tag <ul>
, and then repeatedly inserting subtags into <li>
the tag, resulting in the following HTML
structure:
<ul>
<li>小明</li>
<li>小红</li>
<li>小军</li>
<li>...</li>
</ul>
However, the DOM
operation is not the main content of this article, and the subsequent chapters will introduce it step by step.
There are three types of loop statements: while
, do while
and for
, you can master all loops after reading this article.
while loop
grammar
while
grammar:
while(exp){
//循环体
}
while
The statement mainly includes the execution conditionexp
and the loop body.
The execution condition is usually a conditional expression, e.g. i > 0
indicating that the loop body will be executed only if the variable i
is greater than 0
.
Take a chestnut:
let i = 10;
while(i>0){
console.log(i);//在控制台输出
i--;
}
The above code creates a variable i
and assigns it to ,10
when true, the executing code. The code can output a string on the console, knock on the blackboard, and the console still knows what it is! Then execute , that is , subtract the value of the variable .i > 0
{}
console.log(i);
i--
i
1
To sum up, the function of the above code is to loop the output variables in the browser console i
, from 10
output to 1
.
The code execution result is as follows:
loop condition
Usually, the judgment condition of the loop is a conditional expression. The conditional expression returns a boolean value. When the return value is yes true
, the loop body is executed. When the return value is yes 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 type through implicit conversion Boolean
.
For example i > 0
can be abbreviated as while(i)
:
let i = 3;
while (i) {
// 当 i 变成 0 时,Boolean(i)为false
console.log(i);
i--;
}
Because Boolean(0)
yes, false
the above code is valid.
dangerous loop
The loop condition (variable i
) must continuously perform the minus one operation in each execution process, that is i--
, otherwise i
the value will always be greater than 0
, and the loop will never stop, which is often referred to as an infinite loop .
If there is an infinite loop that is not without solution, we can end the code execution by killing the current process.
The easiest way to do this is to close the browser and go to the console to kill the browser process.
Infinite loop is very dangerous for the program, it will fill up cpu
the resources, even the entire memory space, resulting in a crash.
So, when writing loops, be careful not to forget changes to loop conditions.
A loop with only one line of statements
When there is only one statement in the loop body, the {}
curly braces can be omitted to simplify the code.
To give a short answer to the little plum:
let i = 10;
while(i>0)console.log(i--);
The execution effect is the same as the above code.
do {…} while
grammar
do{
//循环体
}while(exp);
while
Different from the loop, the do {...} while
loop swaps the judgment condition and the loop body. Before judging the loop condition, the loop body will be executed once.
let i = 0;
do {
console.log(i);
i++;
} while (i<10);
The above code will output 0~9
the number, the execution result is as follows:
Characteristics of do {…} while
That is to say, using the do {...} while
statement, the loop body is executed at least once:
let i = 0
do {
console.log(i)
i--;
}while(i>0);
The above code, although i
the execution conditions are not satisfied from the beginning, the loop body will still be executed once.
In fact,
do {...} while
statements are used very rarely in real-world programming!
Because there are very few cases where we still need to execute the loop body once when the judgment condition is not established.
Even when this is the case, we usually use while instead.
for loop
In comparison, the for
loop statement is the most complex, but also the most popular.
grammar
for(begin; exp; step){
//循环体
}
for
It can be confusing to explain directly from a syntax perspective , here is one of the most common cases:
for(let i = 0; i < 10 ; i++){
console.log(i)
}
Comparative interpretation:
grammatical constructs | corresponding sentence | interpret |
---|---|---|
begin |
let i = 0 |
When the loop is executed for the first time, execute once |
exp |
i < 10 |
Before each loop, make a judgment, true execute the loop body, otherwise stop the loop |
step |
i++ |
Execute after each loop body is executed |
The order of execution of the above code is:
let i = 0;
, executed when entering the loop statement, only once;- Judgment
i < 10
, if established, continue to execute, otherwise launch the loop; - Execute
console.log(i)
, the console outputsi
the value of the variable; - Execute
i++
, change the value of the loop variablei
; - Execute the step in a loop
2 3 4
untili < 10
it fails.
In fact, the above code is fully functionally equivalent to:
let i = 0;
while(i < 10){
console.log(i);
i++;
}
condition variable for for
The difference from and while
, is that the condition variable of the loop is defined inside the statement, which is equivalent to a local variable , or an inline variable , such a variable can only be used inside the loop.do {...} while
for
i
for
for
for example:
for(let i = 0; i < 10; i++){
console.log(i);
}
console.log(i); //报错,i is not defined.
As shown below:
The reason for this result is that, i
yes for
, local variables for
are destroyed immediately after the execution of the statement, and subsequent programs cannot be used.
Reminder: If you execute the above code without error, it is very likely that the variable is defined before the for statement
i
.
Of course, we can also not use local variables:
let i = 0;
for(i = 0; i < 10; i++){
console.log(i);
}
console.log(i);// 10
This way we can for
use condition variables outside the statement!
Statement omitted
for
Any part of the statement can be omitted.
For example, omitting the begin
statement:
let i = 0;
for (; i < 10; i++) {
// 不再需要 "begin" 语句段
alert( i );
}
For example, omitting the step
statement:
let i = 0;
for (; i < 10;) {
alert( i++ );//循环变量的修改在循环体中
}
For example, omitting the loop body:
let i = 0;
for (; i < 10;alert( i++ )) {
//没有循环体
}
break
Under normal circumstances, the loop statement needs to wait for the loop condition to be unsatisfied (return false
) before stopping the loop.
But we can break
end the loop early with a statement to force the exit.
for example:
while(1){
//死循环
let num = prompt('输入一个数字',0);
if(num > 9){
alert('数字太大了');
}else if(num < 9){
alert('数字太小了');
}else{
alert('真聪明,循环结束');
break;//结束循环
}
}
The above code is a game of guessing numbers, the loop condition is always, that is 1
to say, the loop will never end, but when the number is entered 9
, the loop will be break
forced to end.
This form of wireless loop addition break
is very common in actual programming scenarios, and it is recommended to write it down in a small notebook.
continue
continue
The currently executing single loop can be stopped and the next loop can be started immediately.
for example:
for(let i = 1;i < 100; i++){
if(i % 7)continue;
console.log(i);
}
The above code outputs 100
all 7
the multiples within, when i % 7
it is not , that is to 0
say, it is i
not 7
a multiple, execute the continue
statement, skip the following statement directly, and execute the next loop.
break/continue label
In the case of multiple loops nesting, there will be such a problem, how to jump out of the entire loop body from the multiple loops?
E.g:
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!')
break label
0
What if we need to let the program execute directly when the user enters alert('Done!')
it?
This requires the use of tags , the syntax is as follows:
label:for(...){
...
break label;
}
break label
Statements can directly and unconditionally jump out of the loop to the label label
.
E.g:
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!');
In the above code, break outer looks up the label named outer and jumps out of the current loop.
Therefore, control is transferred directly from (*)
to alert('Done!')
.
continue label
We can also continue label
directly end the current loop and start the next loop using:
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
You can directly end the outermost loop of multiple loops and start the next loop.
For example, when we (0,0)
type at 0
, then the program will jump directly to (1,0)
the place, instead of break
directly ending the entire loop like this.
Note:
Labels are not random jumps, and must meet certain requirements
E.g:
break label;
label: for(...){
...}
is just incorrect.
after class homework
- Using the
console.log()
method, use the loop to output the following graph:
*
**
***
****
*****
******
- Using a double loop, create a
3X3
matrix and allow the user to enter matrix data.