JavaScript loop while, for, dowhile, break, continue, jump labels

while, for loop

In programming, it is often necessary to use loop statements to handle various repetitive tasks.
For example, using JavaScriptto generate a list of student names requires creating a HTMLtag <ul>, and then repeatedly inserting subtags into <li>the tag, resulting in the following HTMLstructure:

<ul>
<li>小明</li>
<li>小红</li>
<li>小军</li>
<li>...</li>
</ul>

However, the DOMoperation 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 whileand for, you can master all loops after reading this article.

while loop

grammar

whilegrammar:

while(exp){
    
    
	//循环体
}

whileThe statement mainly includes the execution conditionexp and the loop body.

The execution condition is usually a conditional expression, e.g. i > 0indicating that the loop body will be executed only if the variable iis greater than 0.

Take a chestnut:

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

The above code creates a variable iand 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--i1

To sum up, the function of the above code is to loop the output variables in the browser console i, from 10output 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 > 0can be abbreviated as while(i):

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

Because Boolean(0)yes, falsethe 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 ithe 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 cputhe 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);

whileDifferent from the loop, the do {...} whileloop 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~9the number, the execution result is as follows:

Characteristics of do {…} while

That is to say, using the do {...} whilestatement, the loop body is executed at least once:

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

The above code, although ithe execution conditions are not satisfied from the beginning, the loop body will still be executed once.

In fact, do {...} whilestatements 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 forloop statement is the most complex, but also the most popular.

grammar

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

forIt 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, trueexecute 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:

  1. let i = 0;, executed when entering the loop statement, only once;
  2. Judgment i < 10, if established, continue to execute, otherwise launch the loop;
  3. Execute console.log(i), the console outputs ithe value of the variable;
  4. Execute i++, change the value of the loop variable i;
  5. Execute the step in a loop 2 3 4until i < 10it 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 {...} whileforiforfor

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, iyes for, local variables forare 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 foruse condition variables outside the statement!

Statement omitted

forAny part of the statement can be omitted.

For example, omitting the beginstatement:

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

For example, omitting the stepstatement:

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 breakend 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 1to say, the loop will never end, but when the number is entered 9, the loop will be breakforced to end.

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

continue

continueThe 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 100all 7the multiples within, when i % 7it is not , that is to 0say, it is inot 7a multiple, execute the continuestatement, 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

0What 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 labelStatements 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 labeldirectly 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 outerYou 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 breakdirectly 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

  1. Using the console.log()method, use the loop to output the following graph:
*
**
***
****
*****
******
  1. Using a double loop, create a 3X3matrix and allow the user to enter matrix data.

Guess you like

Origin blog.csdn.net/weixin_43302112/article/details/124393600