Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
80
rated 0 times [  87] [ 7]  / answers: 1 / hits: 54944  / 15 Years ago, thu, october 15, 2009, 12:00:00

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;
}

More From » arrays

 Answers
46

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));




[#98502] Monday, October 12, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kieraelsies

Total Points: 718
Total Questions: 103
Total Answers: 104

Location: England
Member since Sun, May 21, 2023
1 Year ago
kieraelsies questions
Tue, Aug 3, 21, 00:00, 3 Years ago
Tue, Feb 23, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Mon, Sep 16, 19, 00:00, 5 Years ago
;