简体   繁体   English

用while循环替换for循环?

[英]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. 目的是使用while循环仅将0到101的偶数打印到网页上。 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. 我已经使用for循环有效地完成了此操作,但是我必须按照说明使用while循环,但我无法正常工作。

The for loop that works: 有效的for循环:

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. 我试图使while循环尽可能类似于for循环,但是当我使用下面的代码时,我的页面甚至都不会加载,更不用说打印数字了。

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. 非常感谢您的帮助,我对JavaScript还是很陌生,如果我使用while循环错误,请不要解雇我。

You almost got it, you only need to change the loop type and add a stopping condition, the internal IF can stay the same: 几乎可以理解,只需更改循环类型并添加停止条件,内部IF即可保持不变:

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. 此外,loopCounter变量不仅应在偶数时始终增加,因此应在IF之外,否则仅在偶数时才递增。 Also also, i think there is no need to check if the loopCounter variable is less than zero in this example. 另外,我认为在此示例中无需检查loopCounter变量是否小于零。 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 将while与if结合

You can modify the code to suit your needs 您可以修改代码以适合您的需求

https://jsfiddle.net/jg972s8p/ 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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