Home>Article>Web Front-end> An article on solving JavaScript loops

An article on solving JavaScript loops

WBOY
WBOY forward
2022-05-12 18:37:31 2844browse

This article brings you relevant knowledge aboutjavascript, 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, useJavaScriptto generate a list of student names. This requires creating aHTML

    tag, and then repeatedly adding it to the tag. Insert the
  • subtag to generate the followingHTMLstructure:

    • 小明
    • 小红
    • 小军
    • ...

    However,DOMmanipulation 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 whileandfor. You will be able to master all loops after reading this article.

    while loop

    Grammar

    whileGrammar:

    while(exp){ //循环体}

    whileThe statements mainly includeExecution conditionexp, and loop body are two parts.

    The execution condition is usually a conditional expression, for examplei > 0means that only when the variableiis greater than0, The loop body will be executed.

    For example:

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

    The above code creates a variableiand assigns it a value of10, wheni > 0 Whenis 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 executei--, that is, the value of variableiminus1.

    To summarize, the function of the above code is to loop out the variableiin the browser console, from10to1.

    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 istrue, the loop body is executed. When the return value isfalse, 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 toBooleantype through implicit conversion.

    For examplei > 0can be abbreviated aswhile(i):

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

    SinceBoolean(0)isfalseSo the above code is established.

    Dangerous infinite loop

    The loop condition (variablei) must be continuously executed and minus one during each execution. Operation, that is,i--, otherwise the value ofiwill always be greater than0, and the loop will never stop, which is often said to beEndless 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 occupycpuresources 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--);

    The execution effect is the same as the above code.

    do {…} while

    The difference between syntax

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

    andwhileloop is thatdo {...} 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);

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

    Features of do {…} while

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

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

    The above code, althoughiIf 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){ //循环体}

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

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

    对比解读:

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

    以上代码的执行顺序是:

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

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

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

    for的条件变量

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

    举个例子:

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

    如下图:

    造成这种结果的原因是,ifor的局部变量,当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('数字太大了'); }else if(num < 9){ alert('数字太小了'); }else{ alert('真聪明,循环结束'); break;//结束循环 }}

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

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

    continue

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

    举个例子:

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

    以上代码输出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!')

    break标签

    如果我们需要在,用户输入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标签

    我们还可以使用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(...){...}

    就是不正确的。

    课后作业

    1. 利用 console.log()方法,使用循环输出以下图形:
    * ** *** **** ***** ******
    1. 利用双重循环,创建一个 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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete