尝试使用isNaN方法清理输入,但它会导致while循环崩溃

时间:2018-05-31 01:44:20

标签: javascript while-loop crash jsfiddle

我正在尝试编写一个项目,要求我提示用户输入一个数字。我已经设置了代码,因此它只接受数字并对它们进行操作,但它直到最后才清理输入。我尝试使用inNaN方法和while循环来保持代码,直到用户输入实数,但是当它识别NaN时,它会崩溃。这是我的代码:

  var userMin = Number(prompt("Name a minimum number to begin your range. 
  Only numbers, please.")); //This is the prompt that asks for the number
  var repuserMin = true; //This is the beginning of the while loop
  while (repuserMin){
  if (isNaN(userMin)) {
  repuserMin = true; //Where the if statement glitches, JSFiddle crashes at this point
  } else {repuserMin = false;}}

2 个答案:

答案 0 :(得分:0)

是的,它会崩溃,因为你试图在那里运行无限循环。

每次循环内部都需要从用户那里获取输入。



var repuserMin = true; //This is the beginning of the while loop
var userMin;
while (repuserMin) {
  userMin = Number(prompt("Name a minimum number to begin your range. Only numbers, please.")); //This is the prompt that asks for the number
  if (isNaN(userMin)) {
    repuserMin = true; //Where the if statement glitches, JSFiddle crashes at this point
  } else {
    repuserMin = false;
  }
}




修改

您需要处理用户不会输入任何内容的情况。 isNaN('') --> false



while (true) {
  var userMin = Number(prompt("Name a minimum number to begin your range. Only numbers, please.")); //This is the prompt that asks for the number  
  if (!isNaN(userMin) && userMin) {
    break;
  }
}




答案 1 :(得分:0)

您需要更改循环中的userMin ,方法是提示用户在条目不是数字时更新值:

var userMin = Number(prompt("Name a minimum number to begin your range. Only numbers, please.")); //This is the prompt that asks for the number

var repuserMin = true; // Trigger the loop by default

while (repuserMin) {
  if (isNaN(userMin)) {
    userMin = Number(prompt("Name a minimum number to begin your range. Only numbers, please."));
  } else {
    repuserMin = false; // Break out of the loop
    console.log('Number was entered');
  }
}