0

I want to declare an array having integer elements 1 to n, where n can be 100 or greater. So, its obvious that I don't want to add all integers (1 to 100) manually.

Can someone suggest me the simplest way to do this in javascript? I think there should be something like this: [1..n], but its not working.

EDIT:

MORE CLARIFICATION OF REQUIREMENT:

I need this: var arr = [1,2,3,4,5,6,7,8,9,10,11,....,100] but I don't want to declare like this where I have to write every element manually. I need something better option to do this.

5
  • 1
    What do you mean? What have you tried? Etc. Point of clarity: arrays are a JavaScript concept, not jQuery - no such thing as a jQuery array. Commented Jul 16, 2012 at 11:59
  • Did you mean javascript array ? Commented Jul 16, 2012 at 12:00
  • yeah sorry, in arrays in javascript Commented Jul 16, 2012 at 12:02
  • @RAJ..., Taz already answered what you need. Commented Jul 16, 2012 at 12:08
  • My example does exactly what you want. First index is i[0], last i[9]. Commented Jul 16, 2012 at 12:16

3 Answers 3

7

You could do this like:

var i = new Array(10); for ( var j = 0; j < i.length; j++) { i[j] = j + 1; } 

Just create an array and fill them with a for loop. You don’t have to declare the var at the beginning.

Check This Example. See the result in the console

Sign up to request clarification or add additional context in comments.

Comments

0

You asked for the simplest way, so it could be as some of many ways

var arr=[1,2,3]; alert(arr[0]); // 1 

or

var arr=[]; arr[0]=1; alert(arr[0]); // 1 

See Taz's answer he has answered what you need, you can go with it.

Comments

-2

If you use underscore.js, I suggest this useful function : http://underscorejs.org/#range

_.range(10); => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

If you play with arrays in your app, you can find other useful usages for underscore.js.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.