HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How to create an array containing 1...N

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arrayhowcontainingcreate

Problem

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


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/

Code Snippets

var foo = new Array(45); // create an empty array with length 45
for(var i = 0; i < foo.length; i++){
  document.write('Item: ' + (i + 1) + ' of ' + foo.length + '<br/>'); 
}

Context

Stack Overflow Q#3746725, score: 561

Revisions (0)

No revisions yet.