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;
}
You can provide a range method in javascript, but you would need to use it a lot to pay for its inclusion in your source code.
var A= Array.from(-5,5)
>>> return value:var B= Array.from(10,100,10)
>>> return value:var C= Array.from('a','z')
>>> return value:Use Array.fill() if you're transpiling or not worried about IE users.
TypeScript
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.
Unfortunately, no, there's no "range" function in Javascript that's comparable to Ruby's, so you'll have to do it with a loop. It looks like what you're doing should work, though.
Use Array.from