Home  >  Q&A  >  body text

javascript - for loop nested two for loops - Stack Overflow

        var h=5;
        for(var i=1;i<=h-1;i++){
            for(var j=h-1;j>=i;j--){
                document.write("&nbsp");
            }
            for(var n=1;n<=2*i-1;n++){
                document.write("*");
            }
            document.write("<br>");
        }

How does this code run? I can understand this code, but I am confused by its operation. The more I think about it, the less I understand how it operates. I am a newbie, please give me some detailed advice. Thank you very much. Thank you. Thank you

我想大声告诉你我想大声告诉你2711 days ago571

reply all(4)I'll reply

  • 巴扎黑

    巴扎黑2017-05-18 10:51:45

    Enter the outer for at first, then the first for in the inner layer, then the second for in the inner layer, and then the first round of loop ends.
    First round output:
        *<br>
    Second round output:
       ***<br>
    Third round output:
      *****<br>
    Fourth round output :
     *******<br>

    reply
    0
  • 迷茫

    迷茫2017-05-18 10:51:45

    for () {    // i=1
        for() {
            // j=4,i=1,write("&nbsp");j=3,i=1,write("&nbsp");
            // j=2,i=1,write("&nbsp");j=1,i=1,write("&nbsp");
        }
        for () {    //n=1,i=1,n<=1就执行
            // n=1,write("<br>");
        }
    }

    The first loop of the outer layer: four spaces and a new line

    for () {    // i=2
        for() {
            // j=4,i=2,write("&nbsp");j=3,i=2,write("&nbsp");
            // j=2,i=2,write("&nbsp");
        }
        for () {    //n=1,i=2,n<=3就执行
            // n=1,write("<br>");n=2,write("<br>");n=3,write("<br>");
        }
    }

    Second outer loop: three spaces, three line breaks

    for () {    // i=3, i<=4就执行
        for() {
            // j=4,i=3,write("&nbsp");j=3,i=3,write("&nbsp");
        }
        for () {    //n=1,i=3,n<=5就执行
            // n=1,write("<br>");n=2,write("<br>");n=3,write("<br>");
            // n=4,write("<br>");n=5,write("<br>");
        }
    }

    The third outer loop: two spaces, five line breaks
    ....

    That is to say, the output space character decreases by one, and the output newline character increases by two. For a messy loop like this, you can try to enumerate two or three execution processes

    reply
    0
  • PHP中文网

    PHP中文网2017-05-18 10:51:45

    Execute in order, enter the outer loop, and then execute the following loop after the inner loop loops

    reply
    0
  • 阿神

    阿神2017-05-18 10:51:45

    You can take a look at the basic syntax of the for statement and calm down and think about it. The outer loop determines the number of line breaks, and the two inner loops determine the number of spaces and * symbols respectively.
    The loops inside are independent and proceed almost simultaneously

    reply
    0
  • Cancelreply