Array with numbers 1-20 [duplicate]

I'm brand new to javascript. I was working through a problem earlier where I needed an array that included the numbers 1 thru 20.

I did this with the following:

var numberArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];

QUESTION:

I can't help but think that this is not efficient (and certainly not scalable). Is there a way to create an array that automatically populates with sequential values between 1 and 20, or 1 and 1000 for instance?

6

2 Answers

Here's a oneliner:

var myArr = Array(20).join().split(',').map(function(a){return this.i++},{i:1});

or a tiny bit shorter:

var myArr = (''+Array(20)).split(',').map(function(){return this[0]++;}, [1]);

Both methods create an empty Array with 20 empty elements (i.e. elements with value undefined). On a thus created Array the map method can't be applied 1, so the join (or string addition) and split trick transforms it to an Array that knows it. Now the map callback (see the MDN link) does nothing more than sending an increment of the initial value ({i:1} or [1]) back for each element of the Array, and after that, myArr contains 20 numeric values from 1 to 20.

Addendum: ES20xx

[...Array(21).keys()].slice(1);

Array.map => See also...

1 Why not? See this SO answer, and this one for a more profound explanation

5

You could use a simple loop to do what you want;

var numberArray = [];
for(var i = 1; i <= 20; i++){ numberArray.push(i);
}
console.log(numberArray); 

You Might Also Like