关于嵌套while循环矩形的问题

时间:2018-11-26 19:56:56

标签: javascript while-loop nested-loops

我正在使用Javascript绘制矩形。不幸的是,我嵌套的外循环似乎无法正常工作。当前(xy)在一行上出现五次,并且不按预期在并发行上重复。

    function Art() { 
// row and col are taking input data from the form in index
    //var row = document.getElementById("row").value; 
    //var col = document.getElementById("height").value; 
    var row=5; 
    var col=3;

    var countrow =1; 
    var countcol =1; 
   document.getElementById("magic").innerHTML=("rectangle has "+ row +" rows and "+ col + " columns");

      while (col> countcol){

           while(countrow<=row){ 
            document.getElementById('count').innerHTML=document.getElementById('count').innerHTML+"(XY)";
            countrow++;
           } 
        document.getElementById('count').innerHTML=document.getElementById('count').innerHTML+"<p></p>"; 
        countcol++; 
    }


}

一次运行的电流输出: (xy)(xy)(xy)(xy)(xy)

有人可以看看我的代码并帮助我理解我的逻辑错误吗?

谢谢。

Expected output

2 个答案:

答案 0 :(得分:2)

您的循环变量countrow第一次到达row的值,但是随后在外部while循环的下一次迭代中,它不会重新启动。因此,内部while将不再执行。

此外,您的循环似乎以错误的顺序放置:您应该首先迭代行,然后每行迭代列。

通过交换循环并在每次迭代中重置内部循环计数器来解决此问题:

var countrow = 1;
while(countrow<=row){ 
    countcol = 1;
    while (countcol<=col){
        document.getElementById('count').innerHTML=document.getElementById('count').innerHTML+"(XY)";
        countcol++;
    } 
    document.getElementById('count').innerHTML=document.getElementById('count').innerHTML+"<p></p>"; 
    countrow++; 
}

最好为此使用标准的for循环(而不是while):

for (let countrow = 0; countrow < row; countrow++){
    for (let countcol = 0; countcol < col; countcol++){
        document.getElementById('count').innerHTML=document.getElementById('count').innerHTML+"(XY)";
    } 
    document.getElementById('count').innerHTML=document.getElementById('count').innerHTML+"<p></p>"; 
}

这至少会使它工作。不过,我应该补充一点,将内容反复添加到innerHTML并不是真正的最佳实践。

在这里,只需分配innerHTML即可完成此操作:

document.getElementById('count').innerHTML=
    Array.from({length: row}, () => "(XY)".repeat(col)).join("<p></p>");

答案 1 :(得分:1)

您应该添加

 countrow =1;  

内部外循环

并更改

col> countcol

col>= countcol

 Art();

     function Art() { 
// row and col are taking input data from the form in index
    //var row = document.getElementById("row").value; 
    //var col = document.getElementById("height").value; 
    var row=5; 
    var col=3;

    var countrow =1; 
    var countcol =1; 
   document.getElementById("magic").innerHTML=("rectangle has "+ row +" rows and "+ col + " columns");

      while (col>= countcol){  ////Change > to >=
            countrow =1;  ////YOU SHOULD ADD JUST THIS
           while(countrow<=row){ 
            document.getElementById('count').innerHTML=document.getElementById('count').innerHTML+"(XY)";
            countrow++;
           } 
        document.getElementById('count').innerHTML=document.getElementById('count').innerHTML+"<p></p>"; 
        countcol++; 
    }


}
<div id=magic></div>
<div id=count></div>