How can I add numbers to an array upside down using 'unshift()'??
I'd like to get an array = {2018, 2017, 2016, 2015, ... , 1999}. because '2018' is this year and '1999' is the debut year of a singer I like. And that's why I'm starting with '1999' which is array[0].
Here is my code using 'push()'. I think it's too long and stupid. I believe there is something I can't come up with. Thank you.
<script>
var years = [1999];
var i = 0;
var n = new Date().getFullYear() - years[i] + 1;
while(i < n){
years.push(years[i]+1);
i++;
}
i=1;
years.reverse();
while(i < years.length){
document.write('<li><a href='+years[i]+'.html>'+years[i]+'</a></li>');
i++;
}
</script>
Something like this?
var years = [1999]; var i = 0; var n = new Date().getFullYear() - years[i]; while (i < n) { years.unshift(years[0]+1); i++; } console.log(years);
This adds the next year to the beginning of the array with unshift()
like you wanted. This removes the need to reverse the array like you did.
Noteworthy here is that we always unshift the value of years[0]+1
since the the array is reversed making the largest number always at index 0.
Why do you even need an array at all?
var currentYear = new Date().getFullYear(); for (var year = currentYear; year >= 1999; year--){ document.write('<li><a href='+year+'.html>'+year+'</a></li>'); }
If I modify your code to generate years
in array. That should be like this with initial year ie debutYear
this.years = function(debutYear) { var currentYear = new Date().getFullYear(), years = []; while ( debutYear <= currentYear ) { years.push(debutYear++); } return years.reverse(); } console.log(years(1999));
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.