2014-02-15 53 views
0

我試圖在數字範圍內找到閏年和非閏年。閏年和非閏年需要放入單獨的數組中,稍後我會將它們輸出到表中。我對JavaScript非常陌生,我懷疑我的循環可能是錯誤的,我不確定。試圖在JavaScript中尋找閏年和非閏年

我的問題是,非閏年數組沒有得到所需的所有數字。我進入1900 - 2000年,閏年似乎沒問題,但非閏年陣列只上升到了1930年。我試圖修復它一段時間,但我沒有運氣。

編輯:for循環只爲我測試數組。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd"> 

<html> 

    <head> 
     <meta http-equiv="content-type" content="text/html; charset=utf-8" /> 

     <title>LeapYears</title> 

     <script type="text/javascript"> 
     /* <![CDATA[ */ 


      function calcLeapYear() { 

       var beginYear = document.leapYears.firstYear.value; 
       var endYear = document.leapYears.secondYear.value; 
       var leapYrs = new Array(); 
       var nonLeapYrs = new Array(); 

       var ctr = 0 
       var ctr2 = 0 
       while (beginYear < endYear){ 

        if (((beginYear % 4 == 0) && (beginYear % 100 != 0)) || (beginYear % 400 == 0)) { /* Determines if year is a leap year or not */ 
         leapYrs[ctr] = beginYear; 
         ++ctr; 
        } 
        else { 
         nonLeapYrs[ctr2] = beginYear; 
         ++ctr2; 
        } 

        ++beginYear; 
       } 

       if (leapYrs == 0){ 
         window.alert("There were no leap years within the range."); 
        } 

       for (i=0;i<leapYrs.length;i++){ //Testing Calculation 
        document.write(leapYrs[i] + "<br/>"); 
       } 

       document.write("<br/>") 

       for (i=0;i<leapYrs.length;i++){ 
        document.write(nonLeapYrs[i] + "<br/>"); 
       } 

      } 

     /* ]]> */ 
     </script> 


    </head> 


    <body> 
     <form name="leapYears"> 

      Beginning Year: <input type="text" name="firstYear" /> End Year: <input type="text" name="secondYear" /> 
      <input type="button" value="Find Leap Years" onclick="calcLeapYear()" /> 

     </form> 

    </body> 


</html> 
+0

''ctr'和'ctr2'的'var'行缺少分號 –

+0

另外,你甚至不需要計數器,你可以使用'leapYrs.push(beginYear)'和類似的方法將一個元素添加到array –

+0

我得看看這個push()方法,剛開始覆蓋數組。 – user3027217

回答

0

你的循環,當你document.writenonLeapYrs的內容遍歷只有leapYrs的長度,因此它只會陣列的打印部分。

+0

我討厭當我想念這樣的小事情。謝謝一堆! – user3027217

+0

如果解決了這個問題,請點擊按鈕接受它作爲答案:) –

+0

完成!再次謝謝你。 – user3027217