簡體   English   中英

我在這里做錯了什么? 否則

[英]What am I doing wrong here? Else if

所以我在這里遇到麻煩。 這是一項作業,基本上我問一個3 + 3是什么的問題,用戶可以在... 6中輸入正確的答案,然后說“正確!”。 如果不是數字,則顯示“請輸入數字...”。如果是5或7,則顯示“非常接近,請重試”。如果不是5 6或7,則顯示“不正確” ”,如果沒有輸入任何內容,則應該說“來吧,你可以做到”。 我在這里做錯了什么???? 目前所做的只是說是,正確的是6! 即使我輸入其他數字

var question;
question = window.prompt("What's the sum of 3+3?", "");

question = parseFloat(question);
if (isNaN(question)) {
  output = "Please enter a number";
} else if (question = 6) {
  output = "Yes " + question + " is correct!";
} else if (question = 5) {
  output = "Very close, try again!";
} else if (question = 7) {
  output = "Very close, try again!";
} else if (question = null) {
  output = "Come on, you can do it!!";
} else {
  output="Incorrect, Please try again"
}

document.write(output);

在您的代碼中,您使用question = 8表示是否將8分配給問題。

=表示分配,==表示比較

嘗試這個 :

 var question; question = window.prompt("What's the sum of 3+3?",""); question = parseFloat(question); if (isNaN(question)) { output= "Please enter a number"; }else if (question==6) { output="Yes " +question+" is correct!"; }else if (question==5){ output="Very close, try again!"; }else if (question==7){ output="Very close, try again!"; }else if (question==null){ output="Come on, you can do it!!"; } else {output="Incorrect, Please try again"} document.write(output); 

正如@Anik Islam Abhi的回答中所指出的,注釋= ==

==是比較運算符( 了解更多

=是賦值運算符( 了解更多信息

現在,您需要確定什么讓用戶什么都不輸入? 我將假設您的意思是任何空白。

您可以做的就是始終從輸入的答案中刪除所有空格,如果用戶仍然沒有輸入任何內容,則您應該打印“來吧,您可以做到!”

 // get the question and remove all whitespace so we know if the user enter an empty string var question = window.prompt("What's the sum of 3+3?","").trim().replace(' ',''); if (!question) { // nothing output = "Come on, you can do it!!"; } else if(isNaN(question)) { // not a number output = "Please enter a number"; } else if (question == 6) { // correct answer output = "Yes " +question+" is correct!"; } else if (question == 5 || question == 7) { // close answer output = "Very close, try again!"; } else { output="Incorrect, Please try again" // incorrect answer } document.write(output); 

暫無
暫無

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

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