繁体   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