views:

196

answers:

3

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;
 }
+1  A: 

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.

Ben Torell
+1  A: 

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;
    }
Justin Johnson
Perfect. I didn't realize you could use the || operator instead of messing with typeof().
r-dub
Ya, but only if false/null is an invalid value for whatever you're working on. This is a very common method to provide a work around for default parameters.
Justin Johnson
A: 

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: (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,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z

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