簡體   English   中英

為什么沒有顯示最后一個 console.log() 輸出?

[英]Why is the last console.log() output not shown?

我正在嘗試使用 JavaScript 制作一個非常簡單的“猜數字”游戲。

我希望它最多有 5 次猜測。 如果你猜,程序會告訴你多少次你得到了答案,如果你超過 5 次就停止游戲。

我只有一個問題。 如果您猜錯了第 5 次,它只會顯示消息“您使用了 5 次猜測,結果是 10” ,我還想顯示您的最后一次猜測以及相應的消息(“走得更高”/“走得更低”) )。

你能幫助我嗎? 出於這個問題的目的,我使用固定變量而不是隨機變量更改了要猜測的數字。

 var solution = 10; var n = prompt("Enter a number"); var i = 1; while ((i < 5) && (n != solution)) { console.log(n + " is too " + ((n < solution) ? "small" : "big")); n = prompt("Try again"); i++; } if (n == solution) { console.log("Good job, the solution was " + n + " you got that in " + i + " tries") } else { console.log(" You lost, your " + i + " tries have ended") }

只需添加以下行:

console.log( n + " is too " + ((n < solution) ? "small" : "big"));

在最后一個 else 語句中,你應該沒問題

 var solution = 10; var n = prompt("Enter a number"); var i = 1; while ((i < 5) && (n != solution)) { console.log(n + " is too " + ((n < solution) ? "small" : "big")); n = prompt("Try again"); i++; } if (n == solution) { console.log("Good job, the solution was " + n + " you got that in " + i + " tries") } else { console.log( n + " is too " + ((n < solution) ? "small" : "big")); console.log(" You lost, your " + i + " tries have ended") }

嘗試這個:

 var solution = 10; var n; var i = 0; // don't read input here, and set i to 0 not 1 while( ( i < 5 ) && ( n != solution)){ if(i==0){n = prompt ("Enter number");} else{n = prompt ("Try again");} console.log( n + " is too " + ((n < solution) ? "small" : "big")); // write that AFTER reading input, not BEFORE. i++; } if ( n == solution ){ console.log("Good job, the solution was " + n + " you got that in " + i + " tries") } else { console.log(" You lost, your " + i + " tries have ended") }

我編輯了你最后的 console.log 語句。 根據我從您的問題中理解的內容,這會產生您想要的結果。

 var solution = 10; var n = prompt("Enter a number"); var i = 1; while ((i < 5) && (n != solution)) { console.log(n + " is too " + ((n < solution) ? "small" : "big")); n = prompt("Try again"); i++; } if (n == solution) { console.log("Good job, the solution was " + n + " you got that in " + i + " tries") } else { console.log(n + " is too " +((n < solution) ? "small." : "high.") + " You lost. Your 5 tries have ended." ) }

暫無
暫無

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

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