javascriptarraysrange

How to create an array containing 1...N


I'm looking for any alternatives to the below for creating a JavaScript array containing 1 through to N where N is only known at runtime.

var foo = [];

for (var i = 1; i <= N; i++) {
   foo.push(i);
}

To me it feels like there should be a way of doing this without the loop.


Solution

  • If I get what you are after, you want an array of numbers 1..n that you can later loop through.

    If this is all you need, can you do this instead?

    var foo = new Array(45); // create an empty array with length 45
    

    then when you want to use it... (un-optimized, just for example)

    for(var i = 0; i < foo.length; i++){
      document.write('Item: ' + (i + 1) + ' of ' + foo.length + '<br/>'); 
    }
    

    e.g. if you don't need to store anything in the array, you just need a container of the right length that you can iterate over... this might be easier.

    See it in action here: http://jsfiddle.net/3kcvm/