Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range of Years in JavaScript for a select box

I'm trying to create a dynamic select box in JavaScript with a range of years starting with 'some' year and ending with the current year. Is there anything like Ruby's range class in JavaScript or do I have to loop trough the years using a for loop?

Here's what I've come up with though I think it's a bit much considering in Ruby I can just use a range.

    this.years = function(startYear){         startYear = (typeof(startYear) == 'undefined') ? 1980 : startYear         var currentYear = new Date().getFullYear();         var years = []         for(var i=startYear;i<=currentYear;i++){             years.push(i);         }          return years;     } 
like image 674
rwilliams Avatar asked Oct 15 '09 21:10

rwilliams


2 Answers

JavaScript does have a Range object, but it refers to an arbitrary portion of the DOM and is not supported in IE 6/7.

If you want, you can simplify your function to this, but it's all the same really.

this.years = function(startYear) {      var currentYear = new Date().getFullYear(), years = [];      startYear = startYear || 1980;        while ( startYear <= currentYear ) {          years.push(startYear++);      }         return years;  }     console.log( this.years(2019-20));
like image 135
Justin Johnson Avatar answered Sep 18 '22 08:09

Justin Johnson


Use Array.from

const currentYear = (new Date()).getFullYear(); const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step)); console.log(range(currentYear, currentYear - 50, -1));  // [2019, 2018, 2017, 2016, ..., 1969]
like image 30
J. Jerez Avatar answered Sep 19 '22 08:09

J. Jerez