SongD
SongD

Reputation: 23

How can I add numbers to array simply using unshift()?

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

Answers (3)

A l w a y s S u n n y
A l w a y s S u n n y

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

Blue
Blue

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

Chris
Chris

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

Related Questions