簡體   English   中英

如何在javascript中為“確認”警報進行連續循環

[英]How do I make a continuous loop for "confirm" alert in javascript

所以我對 Javascript 有點陌生,如果這個問題聽起來很基本,那么抱歉。 所以我試圖制作一個猜謎游戲,讓計算機猜出用戶在想的數字。 我想讓它無論用戶點擊“取消”多少次都會顯示一個新的隨機數,直到計算機“猜測”用戶正在思考的數字。 但我不知道如何制作一個循環。

這是我的代碼:

const guesser = () => {
let min = 0;
let max = 100;
let guess;

alert("Think of a number between 0 and 100");
while (min <= max) {
    guess = Math.round((min + max) / 2);
    if(confirm("is your number " + guess) == false){
       if(confirm("if your number is higher, please click 'ok'. If its lower please click 'cancel'") == false){
          if (confirm("is your number " + Math.floor(Math.random() * guess)) == true){
              alert("haha got your number!")
            }
          }
        else if (confirm("is your number " + Math.floor((Math.random() * 50) + guess)) == true){
                alert("haha got your number!")
            }
       }
else {
    alert("haha got your number!")
    }
    return;

}

alert("I could not guess your number. I think you are cheating!");
  };

您要求用戶告訴您他們的數字是高於還是低於您的猜測,但您需要對這些信息進行處理。 具體來說,如果他們的數量大於當前猜測,則通過將最小值提高到當前猜測來增加猜測。 如果他們的數量小於當前猜測,則通過將最大值降低到當前猜測來減少猜測。

 function main() { var min = 0; var max = 100; alert(`Think of a number between ${min} and ${max}`); while (min<max) { var guess = Math.round((min + max) / 2); if(confirm("is your number " + guess)) { alert("haha got your number!") return; } else { if(confirm("if your number is higher, please click 'ok'. If its lower please click 'cancel'")) { min = guess+1; } else { max = guess-1; } } } alert("I could not guess your number. I think you are cheating!"); } main();

這是實現您正在尋找的另一種方法:

 document.addEventListener("DOMContentLoaded", function(event) { const guesser = () => { let min = 0; let max = 100; let guess; alert("Think of a number between 0 and 100"); while (min <= max) { // initial guess guess = Math.round((min + max) / 2); if (confirm("is your number " + guess) == false) { if (confirm("if your number is higher, please click 'ok'. If its lower please click 'cancel'") == false) { // number is lower than guess max = guess; } else { // number is higer than guess min = guess } } else { alert("guessed your number!") return } } } guesser(); });
 <html> <head> </head> <body> Hello World! </body> </html>

暫無
暫無

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

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