我有一个提示问题的变量。我想确保对方回答的是数字而不是“五”。但也要发出警告消息,表明该号码无效,并再次询问问题。我还是个新手,相信我做错了。这是我到目前为止所拥有的。
var question = prompt("Enter a number");
for(i=0; i = question; i++){
if{
typeof question != "number");
console.log("question not number");
alert("Please try again");
}
最佳答案
您可以创建一个提出问题的函数。如果答案不满足您,您可以再次调用该函数本身。
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
关于Javascript:创建循环来检查变量是否为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35344949/