简体   繁体   中英

Replace for loop with a while loop?

The objective is to print only even numbers from 0 to 101 to a webpage using a while loop. I've effectively done this with a for loop, but I must use a while loop as instructed and I can't get that to work.

The for loop that works:

for (var loopCounter = 0; loopCounter >= 0 && loopCounter <= 101; loopCounter++){
    if (loopCounter % 2 == 0){
        document.write(loopCounter + '<br/>')
    }
}

I tried to make the while loop as similar to the for loop as possible, but when I use the code below, my page won't even load let alone print the numbers.

var loopCounter = 0;
while (loopCounter >= 0 && loopCounter <= 101){
    while (loopCounter % 2 == 0){
        document.write(loopCounter + "<br/>");
        loopCounter++;
    }
}

Any help is greatly appreciated, also I'm very new to JavaScript, please don't flame me if I'm using the while loop wrong.

You almost got it, you only need to change the loop type and add a stopping condition, the internal IF can stay the same:

var loopCounter = 0;
while (loopCounter <= 101){
    if (loopCounter % 2 == 0){
        document.write(loopCounter + "<br/>"); 
    }
    loopCounter++;
}

Also, the loopCounter variable should increase always not only when the number is even, so it should be outside the IF or else it will only increment there is even number. Also also, i think there is no need to check if the loopCounter variable is less than zero in this example. Hope I helped

let loopCounter = 0;
while (loopCounter <= 101){
   //Change the second while for an if.
    if (loopCounter % 2 == 0){
        document.write(loopCounter + "<br/>");
    }
    // Also, you must place the loopCounter++ after the if statement.
    loopCounter++;
}

See this example, why make it difficult ? Combine the while with an if

You can modify the code to suit your needs

https://jsfiddle.net/jg972s8p/

<script>
function myFunction() {
var tmp = "";
var loopCounter = 0;
while (loopCounter >= 0 && loopCounter <= 101){
    if (loopCounter % 2 == 0)
  {
        tmp = tmp + loopCounter.toString() + "<br>";
    }
        loopCounter++;
    }
    return tmp
}
document.getElementById("demo").innerHTML = myFunction();
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM