簡體   English   中英

我的JavaScript for循環if / else語句怎么了?

[英]What is wrong with my JavaScript for loop if/else statement?

為什么我的代碼不起作用? 當我正確輸入數字時,它不會向我顯示window.alert ,它是正確的。

這是問題所在:編寫一個在1到10之間選擇一個隨機數的程序。給用戶5個猜測(使用循環)來猜測該數字。 如果他們錯了,請告訴他們。 如果它們是正確的,則告訴他們並退出循環。 在程序末尾,向他們顯示實際數字。

<script>
    var num = Math.floor(Math.random()*10 + 1);

    var guess = parseInt(window.prompt("Enter a number!"));
    for (var x=1; x<=5; x++) {
         if (num == guess) {
             window.alert("You are right!");
             break;
         }
         else {
             window.prompt("You were wrong, try again!");
             continue;
         }
    }
    document.write("The number was "+num);
</script>

您沒有使用后續猜測。 在循環內重新提示時,您需要更新guess

    guess = parseInt(window.prompt("You were wrong, try again!"));
//  ^^^^^^^^^^^^^^^^^-------------------------------------------^

例:

 var num = Math.floor(Math.random() * 10 + 1); var guess = parseInt(window.prompt("Enter a number!")); for (var x = 1; x <= 5; x++) { if (num == guess) { window.alert("You are right!"); break; } else { guess = parseInt(window.prompt("You were wrong, try again!")); continue; } } console.log("The number was " + num); 


另外:在頁面的主要解析完成后(或實際上完全沒有),不要使用document.write 而是使用DOM向頁面添加元素以顯示要顯示的內容。

另外,由於循環中沒有其他內容,因此不需要continue

然后是Ben Snaize的觀點 :該代碼實際上使用戶猜測了6次,盡管它拋棄了最終的猜測。

基於@Milaci的答案版本,僅有5個猜測。 此外,它現在可以正確使用最后的猜測。

  var num = 5; //Math.floor(Math.random()*10+1); var guess = parseInt(window.prompt("Enter a number!")); if (num === guess) { window.alert("You are right!"); } else { for (var x = 1; x < 5; x++) { guess = parseInt(window.prompt("You were wrong, try again!")); if (num === guess) { window.alert("You are right!"); break; } } } document.write("The number was " + num); 

您正在生成一個隨機數,然后得到一個猜測,然后循環五次以查看兩個數字是否相同。 您應該在循環內得到一個新的猜測。

您應該使用兩次猜測,一次是第一次,另一次是在for循環內,以獲取用戶插入的值。 我使用靜態5值來方便測試

 var num=5;//Math.floor(Math.random()*10+1);
 var guess=parseInt(window.prompt("Enter a number!"));

for(var x=1; x<=5; x++){

    if (num==guess){
        window.alert("You are right!");
        break;

    }

    else{
        guess=parseInt(window.prompt("You were wrong, try again!"));
    } 
}

document.write("The number was "+num);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM