簡體   English   中英

用while循環替換for循環?

[英]Replace for loop with a while loop?

目的是使用while循環僅將0到101的偶數打印到網頁上。 我已經使用for循環有效地完成了此操作,但是我必須按照說明使用while循環,但我無法正常工作。

有效的for循環:

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

我試圖使while循環盡可能類似於for循環,但是當我使用下面的代碼時,我的頁面甚至都不會加載,更不用說打印數字了。

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

非常感謝您的幫助,我對JavaScript還是很陌生,如果我使用while循環錯誤,請不要解雇我。

幾乎可以理解,只需更改循環類型並添加停止條件,內部IF即可保持不變:

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

此外,loopCounter變量不僅應在偶數時始終增加,因此應在IF之外,否則僅在偶數時才遞增。 另外,我認為在此示例中無需檢查loopCounter變量是否小於零。 希望我能幫上忙

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++;
}

看這個例子,為什么很難? 將while與if結合

您可以修改代碼以適合您的需求

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