JavaScript years range for window selection

I am trying to create a dynamic selection block in JavaScript with a number of years, starting from "some" year and ending with the current year. Is there something like a Ruby range class in JavaScript, or do I need to loop through the years using a for loop?

Here is what I came up with, although I think this is a bit like 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; } 
+12
javascript arrays range
source share
4 answers

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

If you want, you can simplify your function before that, but actually it doesn't matter.

 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)); 
+33
source share

Unfortunately, no, there is no "range" function in Javascript that is comparable to Ruby's, so you have to do it with a loop. It seems that what you are doing should work.

+1
source share

You can provide a range method in javascript, but you will have to use it a lot to pay to include it in your source code.

var A= Array.from(-5,5) >>> return value:

(Array) -5, - 4, -3, - 2, -1, 0,1,2,3,4,5

var B= Array.from(10,100,10) >>> return value:

(Array) 10,20,30,40,50,60,70,80,90,100

var C= Array.from('a','z') >>> return value:

(Array) a, b, c, d, e, f, f, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x , y, g

 Array.from= function(what, n, step){ var A= []; if(arguments.length){ if(n){ return A.range(what, n, step) } L= what.length; if(L){ while(L){ A[--L]= what[L]; } return A; } if(what.hasOwnProperty){ for(var p in what){ if(what.hasOwnProperty(p)){ A[A.length]= what[p]; } } return A; } } return A; } Array.prototype.range= function(what, n, step){ this[this.length]= what; if(what.split && n.split){ what= what.charCodeAt(0); n= n.charCodeAt(0); while(what<n){ this[this.length]= String.fromCharCode(++what); } } else if(isFinite(what)){ step= step || 1; while(what <n) this[this.length]= what+= step; } return this; } 
+1
source share

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] 
0
source share

All Articles