0

I want to create an array with numbers from 1 to n. For example if my n number is 8 I need my list array to be:

[1,2,3,4,5,6,7,8]

Of course it could be done with for loop, like so:

var n = 8;
var list = [];
for(var i=1;i!=n+1;i++){
    list.push(i);
}

But is there some unique way to do this?

I have also tried new Array(8) but it didn't do what it need:

[ , , , , , , , ]
Michael
  • 15,386
  • 36
  • 94
  • 143
  • I guess, a loop is the only way - but if you're willing to use libraries for this, take a look at [lodash's range function](http://lodash.com/docs#range). – naeramarth7 Sep 17 '14 at 11:22
  • There is no more elegant way to do it than the array. Unless you know the elements from the beginingm, then you can use var arr=[1,2,3,4,5,6,7,8] – Manjar Sep 17 '14 at 11:22
  • https://github.com/lodash/lodash/blob/2.4.1/dist/lodash.compat.js#L5067 – CD.. Sep 17 '14 at 11:23
  • `(new Array(9)).join('x').split('').map(function(_, i) { return i+1; });` – adeneo Sep 17 '14 at 11:29
  • Take a looks at duplicated post, there are probably all possible ways. – dfsq Sep 17 '14 at 11:29

0 Answers0