JavaScript仅显示最后结果

时间:2019-08-30 13:23:23

标签: javascript html

我正在尝试打印1月1日 st 的星期日的年份。问题是它只显示最后一个结果。

function sun() {
  var sunday = new Date();
  var year;
  for (year = "2014"; year <= 2050; year++) {
    var date = new Date(year, 0, 1);
    if (date.getDay() == 0)
      document.getElementById('demo').innerHTML = "First Jan being sunday on year =" + year + "<br>";
  }
}
<input type="submit" id="submit" onclick="sun()">

4 个答案:

答案 0 :(得分:2)

在循环的每次迭代中这些值都将被替换。

连接结果会有所帮助。

在表达式中使用运算符+:

document.getElementById('demo').innerHTML += "First Jan being sunday on year ="+year+"<br>"; 

答案 1 :(得分:1)

在表达式中添加+

 document.getElementById('demo').innerHTML += "First Jan being sunday on year ="+year+"<br>"; 

答案 2 :(得分:1)

function sun(){

var sunday = new Date();
var year;

for (year = "2014"; year <= 2050; year++){
    var date = new Date(year,0,1);
    if (date.getDay()==0)
    //you are overwriting the content of 'demo' each time, changed to "+=" so it adds new HTML each time
    document.getElementById('demo').innerHTML += "First Jan being sunday on year ="+year+"<br>"; 
}

}

答案 3 :(得分:1)

您应在“ #demo” div中静态放置“ 1月1日将是星期日:”,然后使用+=而不是=将年份串联起来,例如

function sun() {
  for (let year = 2014; year <= 2050; year++) {
    if ((new Date(year, 0, 1)).getDay() == 0) {
      document.getElementById('demo').innerHTML += " " + year;
    }
  }
}
<input type="submit" id="submit" onclick="sun()">
<div id="demo">January 1st will be on Sunday in:</div>