所以我在这里遇到麻烦。这是一个任务,基本上我问一个问题是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);
答案 0 :(得分:2)
在您的代码中,您的用户问题= 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);
答案 1 :(得分:1)
如@Anik Islam Abhi所述,答案和评论=
与 ==
不同。
==
是一个比较运算符(read more)
=
是一个赋值运算符(read more)
现在,您需要做的是决定用户输入 nothing 的方法是什么? 我假设你的意思是任何数量的空白。
您可以做的是始终从输入的答案中删除所有空格,如果用户仍然输入 nothing 那么您就知道应该打印“来吧,你可以做到!!”
// 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);