2015-05-19 94 views
0

我想列出格式的所有日期和小時mmddhh輸出所有日期的一年

Q1:爲什麼我在輸出之前得到「undefined」?我該如何解決它?

var m, d, h, month, day, hour, output; 
 
for (m = 1; m <= 12; m++) { 
 
    month = addZero(m).toString(); 
 
    for (d = 1; d <= 31; d++) { 
 
     day = addZero(d).toString(); 
 
     for (h = 1; h <= 24; h++) { 
 
      hour = addZero(h).toString(); 
 
      output += month + day + hour + "<br>"; 
 
     } 
 
    } 
 
} 
 
document.getElementById("result").innerHTML = output; 
 

 
function addZero(z) { 
 
    var z 
 
    if (z < 10) 
 
     return "0" + z; 
 
    else 
 
     return z; 
 
}
<p id="result"></p>

Q2:我嘗試使用d 31倍if (m = "01" || "03" || "05" || "07" || "08" || "10" || "12")其他循環30次循環。然而,這是失敗的,我該怎麼做?

var m, d, h, month, day, hour, output; 
 
    for (m = 1; m <= 12; m++) { 
 
     month = addZero(m).toString(); 
 
     if (m = "01" || "03" || "05" || "07" || "08" || "10" || "12") { 
 
      for (d = 1; d <= 31; d++) { 
 
       day = addZero(d).toString(); 
 
       for (h = 1; h <= 24; h++) { 
 
        hour = addZero(h).toString(); 
 
        output += month + day + hour + "<br>"; 
 
       } 
 
      } 
 
     } else { 
 
      for (d = 1; d <= 30; d++) { 
 
       day = addZero(d).toString(); 
 
       for (h = 1; h <= 24; h++) { 
 
        hour = addZero(h).toString(); 
 
        output += month + day + hour + "<br>"; 
 
       } 
 
      } 
 
     } 
 
    } 
 
    document.getElementById("result").innerHTML = output; 
 

 

 
    function addZero(z) { 
 
     var z 
 
     if (z < 10) 
 
      return "0" + z; 
 
     else 
 
      return z; 
 
    }
<p id="result"></p>

回答

0

您已經聲明瞭一個名爲output變量,但它不是一個值初始化,所以它的價值是不確定的。

然後,當你說output += month + day + hour + "<br>";真的是output = undefined + month + day + hour + "<br>";,因此你在output

var m, d, h, month, day, hour, output = ""; 
 
for (m = 1; m <= 12; m++) { 
 
    month = addZero(m).toString(); 
 
    for (d = 1; d <= 31; d++) { 
 
    day = addZero(d).toString(); 
 
    for (h = 1; h <= 24; h++) { 
 
     hour = addZero(h).toString(); 
 
     output += month + day + hour + "<br>"; 
 
    } 
 
    } 
 
} 
 
document.getElementById("result").innerHTML = output; 
 

 
function addZero(z) { 
 
    var z 
 
    if (z < 10) 
 
    return "0" + z; 
 
    else 
 
    return z; 
 
}
<p id="result"></p>

+0

THX你的答案的開始得到一個undefined爲Q1 您能幫我嗎解決Q2問題? – Ming

+0

@Ming'm ==「01」|| m ==「03」|| m ==「05」|| m ==「07」|| m ==「08」|| m ==「10」|| m ==「12」' –

+0

@Ming http://jsfiddle.net/arunpjohny/81x13ne2/2/ –

相關問題