当我声明if语句以检查用户是否输入数字而不是直接字或字母时,它会说“不是有效输入,请输入您的回复作为数字。”但是,一旦你在警告框中单击“确定”,当它显示该消息时,您在提示中键入的消息是错误的或者数字仍然会被放入对象中。
如果你输入其他数字而不是数字,我怎么能这样做呢?它会继续说“不是有效的输入,请输入你的回复作为数字”,直到你输入数字?
var storeUsersInfo = [];
var amountOfUsers = prompt("How many users do you want?");
amountOfUsers = parseInt(amountOfUsers);
function returnUserInput() {
var askFirstName = prompt("What is your first name?");
var askLastName = prompt("What is your last name" + " " + titleCase(askFirstName) + "?");
var askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
if(!Number.isInteger(Number.parseInt(askAge))) {
alert("Not a valid input, please enter your response as a number.");
};
return {
firstName: titleCase(askFirstName),
lastName: titleCase(askLastName),
age: askAge
};
};
function titleCase(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
};
for(var i = 0; i < amountOfUsers; i++) {
storeUsersInfo[i] = returnUserInput();
}
console.log(storeUsersInfo);
答案 0 :(得分:0)
而是以递归方式再次向您的函数显示警报调用。
if(!Number.isInteger(Number.parseInt(askAge))) {
returnUserInput()
};
它会一次又一次地提示,直到反应没问题。
答案 1 :(得分:0)
将prompt
,检查和alert
置于循环中:
function returnUserInput() {
var askFirstName = prompt("What is your first name?");
var askLastName = prompt("What is your last name" + " " + titleCase(askFirstName) + "?");
while (true) {
var askAge = prompt("How old are you" + " " + titleCase(askFirstName)
+ " " + titleCase(askLastName) + "?");
if(Number.isInteger(Number.parseInt(askAge))) break; // OK, exit loop
alert("Not a valid input, please enter your response as a number.");
};
return {
firstName: titleCase(askFirstName),
lastName: titleCase(askLastName),
age: askAge
};
};