我正在测试此代码以确保用户只添加一个数字,当他这样做时,我想提醒该号码。 如果我在第一次提示时只测试字母,然后在第二次提示时更改为数字,它仍然给我一个NaN。 如何纠正这个:
var mynum = prompt("Enter the number you wish");
function isitanumber(numb){
while (isNaN(numb) == true){
numb = prompt("Please add a valid number");
}
}
isitanumber(mynum);
alert("The number you have added is " + mynum);
答案 0 :(得分:2)
您的代码应该可以正常运行。你忘了从第二个提示中获取值。这可能有效:
var mynum = prompt("Enter the number you wish");
function isitanumber(numb){
while (isNaN(numb) == true){
numb = prompt("Please add a valid number");
}
//This sets the value you are displaying to the new input
mynum = numb;
}
isitanumber(mynum);
alert("The number you have added is " + mynum);
此代码正在运行:https://jsfiddle.net/ruvn2uf0/
答案 1 :(得分:1)
我最好的猜测是,一旦用户在初始mynum
输入任何文字,您的prompt
变量就无法获得更新后的值。所以我建议你每次从调用函数返回值return
并更新你的全局变量。
var mynum = prompt("Enter the number you wish");
function isitanumber(numb) {
while (isNaN(numb)) {
return parseInt(prompt("Please add a valid number")); //return
}
}
mynum = isitanumber(mynum); //update the variable
alert("The number you have added is " + mynum);

在这种情况下您也可以使用do-while
,如下所示:
var mynum;
do{
mynum = parseInt(window.prompt("Please enter a number", ""));
}while(isNaN(mynum));
alert("The number you have added is " + mynum);