我想列出格式为mmddhh
的所有日期和小时Q1:为什么我在输出之前得到“未定义”?我该如何解决?
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
循环播放if (m = "01" || "03" || "05" || "07" || "08" || "10" || "12")
31次,否则循环播放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 :(得分:0)
您已声明一个名为output
的变量,但未使用值初始化,因此其值未定义。
然后,当你说output += month + day + hour + "<br>";
它真的是output = undefined + month + day + hour + "<br>";
时,你就会在undefined
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;
}
&#13;
<p id="result"></p>
&#13;