Reputation: 23
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>
Upvotes: 1
Views: 70
Reputation: 38542
If I modify your code to generate years
in array. That should be like this with initial year i.e debutYear
this.years = function(debutYear) {
var currentYear = new Date().getFullYear(), years = [];
while ( debutYear <= currentYear ) {
years.push(debutYear++);
}
return years.reverse();
}
console.log(years(1999));
Upvotes: 0
Reputation: 22911
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>');
}
Upvotes: 2
Reputation: 59531
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.
Upvotes: 2