2017-02-26 105 views
0

我正在使用JS Bin網站來寫這個。做while循環時不提示。 Javascript

循環火災只有當我給個差(數字)輸入一次:

function isInputLeapYear() 
{ 
    var year = -1; 

    var inputOk = true; 

    do{ 
     year = prompt("Please enter a year to check if it is a leap year \ninput year between 0-9999"); 

     if(year < 0 || 9999 < year) // check input 
     { 
     inputOk = false; 
     alert("\""+year+"\" is not a good year. \nThe input needs to be between 0-9999");    
     }; 


    }while(inputOk === false); 


    .... 
} 
+2

的'prompt'函數返回一個'string',而不是一個'number'。您可以查看['parseInt'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt)函數。 –

+1

您需要添加一個'else {inputOk = true; '',否則你的代碼對我來說工作得很好。 – 4castle

+0

@DarinDimitrov是正確的。使用parseInt函數。 year = parseInt(輸入)。 –

回答

-2

移動了var inoutOK = true進入死循環再次提示之前復位的方式。

function isInputLeapYear() 
{ 
    var year = -1; 

    do { 
     var inputOk = true; 
     year = prompt("Please enter a year to check if it is a leap year \ninput year between 0-9999"); 

     if(year < 0 || 9999 < year) // check input 
     { 
      inputOk = false; 
      alert("\""+year+"\" is not a good year. \nThe input needs to be between 0-9999");    
     }; 


    } while(inputOk === false); 


    .... 
} 
+1

代碼轉儲不是有用的答案。說*你改變了什麼,以及*爲什麼*。 –

+0

@ T.J.Crowder謝謝你不知道。我編輯了答案。 – MotKohn

-2
function isInputLeapYear() 
    { 
     var year = -1; 

     var inputOk = false; 

     do{ 
      year = prompt("Please enter a year to check if it is a leap year \ninput year between 0-9999"); 

      if(year > 0 && 9999 > year) // check input 
      { 
      inputOk = True; 



      else 
{ 
alert("\""+year+"\" is not a good year. \nThe input needs to be between 0-9999"); 
} 
      }; 


     }while(inputOk === false); 


     .... 
    } 
+0

代碼轉儲不是有用的答案。說*你做了什麼,以及*爲什麼*。 (併合理地格式化代碼。) –

+0

另請注意,您已更改範圍。您不能只是將'year <0'更改爲'year> 0'來反轉該條件。這是'year> = 0'。 –