最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Nested while loops in javascript - Stack Overflow

programmeradmin4浏览0评论

I'm trying to make a grid of stars with a nested while loop.

It does work with a for loop:

for(m = 1; m <= 5; m++) {
    for(n = 1;n <= 10; n++) {
        document.write("*" + " ");
    }
    document.write("<br>");
}

but I can't figure out how I can solve it with a while loop:

while(m <= 5) {
    while(n <= 10) {
        document.write("*" + " ");
        n++;
    }
    document.write("<br>");
    m++;
}

Does anyone have any idea?

Thnx

I'm trying to make a grid of stars with a nested while loop.

It does work with a for loop:

for(m = 1; m <= 5; m++) {
    for(n = 1;n <= 10; n++) {
        document.write("*" + " ");
    }
    document.write("<br>");
}

but I can't figure out how I can solve it with a while loop:

while(m <= 5) {
    while(n <= 10) {
        document.write("*" + " ");
        n++;
    }
    document.write("<br>");
    m++;
}

Does anyone have any idea?

Thnx

Share Improve this question asked Apr 2, 2016 at 15:38 YawuarYawuar 591 gold badge2 silver badges8 bronze badges 1
  • 1 Well, did you declare and initialise n and m anywhere? – Siguza Commented Apr 2, 2016 at 15:40
Add a ment  | 

2 Answers 2

Reset to default 4

You're missing the initializers. m needs to start and 1, and n needs to restart at 1 every time m is incremented.

var m, n;
m = 1;
while(m <= 5) {
    n = 1;
    while(n <= 10) {
        document.write("*" + " ");
        n++;
    }
    document.write("<br>");
    m++;
}

The problem is that you do not reset the n variable, so everytime it is 10 and thus not entering the while loop. You need to do:

var m = 0,
    n = 0,
    div = document.getElementById('draw');

function writeToDiv(stringToWrite) {
  div.innerHTML = div.innerHTML + stringToWrite;
}

while (m <= 5) {
  while (n <= 10) {
    writeToDiv("*" + " ");
    n++;
  }
  n = 0;
  writeToDiv("<br>");
  m++;
}
<div id="draw">

</div>

发布评论

评论列表(0)

  1. 暂无评论