为两个输入变量简化我的isNaN函数 - JavaScript

时间:2015-11-15 01:30:42

标签: javascript function prompt

我有两个变量我正在通过两个提示。一个是startNum,另一个是rangeNum。我试图错误捕获它,以便如果它们不是正数,它将重新提示用户,直到给出一个正值。目前我通过为每个vaiable运行一个isnan来工作,但我想知道我是否可以只有一个函数检查两个提示输入的数字是否为正,如果没有,它将重新提示给用户正确的提示。提前感谢您的任何帮助/答案。

function isPosNum() {

    startNum = parseInt(prompt("Please enter a positive starting value"));


    if (isNaN(startNum)) {
        return NaN;
    } else if (startNum < 0) {
        console.log('failed');
        alert('That is not a positive number. Please try again and enter a positive number.');
        return "negative";
        isPosNum();

    } else if ( startNum > 0) {
        console.log('worked');
        //push initial value to the array
        numArray.push(startNum);
        //enterRange();
        return "positive";

    } else {
        return "zero";
    } 

    function enterRange() {
        rangeNum = parseInt(prompt("Please enter a number to determine the range of values."));

        if (isNaN(rangeNum)) {
            return NaN;
        } else if (rangeNum < 0) {
            console.log('failed');
            alert('That is not a positive number. Please try again and enter a positive number.');
            return "negative";
            enterRange();

        } else if ( rangeNum > 0) {
            console.log('worked');
            //push initial value to the array
            //collatz();
            return "positive";

        } else {
            return "zero";
        }

    }

}

由于deamentiaemundi的回答,我能够得到代码。这是我希望看到的人的最终代码。

function getStartNum(){

   startNum = parseInt(prompt('Please enter a starting number greater than 0.'));

   if(!isPosNum(startNum)){
      alert("error! That is an incorrect value. Please renter an appropriate positive value.");
      getStartNum();
   } else {
    getRangeNum();
   }

}

function getRangeNum(){

   rangeNum = parseInt(prompt('Please enter a range value greater than 0'));
   if(!isPosNum(rangeNum)){
      alert("error! That is an incorrect value. Please renter an appropriate positive value.");
      getRangeNum();
   }
   // and so on
}

function isPosNum( number ) {

    if (isNaN( number )) {
        return false;
    } else if (number < 0) {
        return false;
    } else if (number == 0) {
        return false;
    } else {
        return true;
    }

}

1 个答案:

答案 0 :(得分:1)

创建一个函数checkRange(number),它将数字作为参数,并根据该数字返回truefalse。 第二个功能是带有提示的功能。

function getNumbers(){
   startNum = parseInt(prompt('Please enter a number'));
   if(!checkRange(startNum)){
      alert("error!");
      getNumbers();
   }s
   rangeNum = parseInt(prompt('Please enter a range'));
   if(!checkRange(rangeNum)){
      alert("error!");
      getNumbers();
   }
   // and so on
 }