简体   繁体   中英

JavaScript showing only last result

I am trying to print the years in which Sunday comes in 1 st January. The problem is that it's only showing the last result.

 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()"> 

将+添加到表达式中

 document.getElementById('demo').innerHTML += "First Jan being sunday on year ="+year+"<br>"; 
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>"; 
}

}

The values are getting replaced in each iteration of the loop.

Concatenating the result is going to help.

Use the operator + in the expression:

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

You should put "January 1st will be on Sunday in:" statically inside the '#demo' div , then concatenate the years by using += instead of = , eg :

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM