我有一个提示问题的变量。我想确保这个人用数字回答,而不是"五。"但是也要发出一条警告信息,说明它不是有效号码,并再次提出问题。我还是新人,相信我做错了。这是我到目前为止所拥有的。
{{1}}
答案 0 :(得分:2)
您可以提出问题的功能。如果答案不满足你,你可以再次调用这个函数。
var askQuestion = function() {
var response = prompt("Enter a number");
// if it is good, return true (insert your condition in the if)
if(true) {
return true;
}
// If it is not good, recall the function, so it recall the question
else {
return askQuestion();
}
}
然后在您的代码中,执行以下操作:
if(askQuestion()) {
// The person answered what you want
}
// There is no else because it prompt the question all the time
// if the answer is not what you are excepting
答案 1 :(得分:0)
您可以检查某个值是否为使用parseInt()
解析它的数字,然后实际检查它是否为isNaN()
的数字。这将有效:
var question = prompt("Enter a number");
if (isNaN(parseInt(question))) {
console.log("question not number");
alert("Please try again");
}
答案 2 :(得分:0)
循环直到输入为整数的方式:
var question;
while (isNaN(parseInt(question = prompt("Enter a number"))))
{
console.log("Question is not a number");
alert("Please try again");
}
答案 3 :(得分:0)
您可以使用isNaN()检查用户输入是否不是数字。这意味着您可以使用!isNaN()来检查用户输入是否为数字。
function isValidAns(ans){
if(isNaN(ans)) return false;
if(ans == 5) return false;
return true;
}
您可能还需要一个while循环来让用户一次又一次地输入,直到输入有效。
var ans = "";
while(true){
ans = prompt("Enter a number");
if(isValidAns(ans)){
break;
}else{
alert("Please try again.")
}
}