Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

Hello,

I just want to create an array of numbers counting from 1 to a given number.

At the moment I have the for loop running like this:

var i=0;
for (i=1;i<=10;i++)
{
if (i == 1)
{
document.write(i);
} else {
document.write(", " + i);
}
}

This outputs 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

How can I put this output into this variable: 'var ids' so I get out

var ids= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

I'm a bit of a novice so any help would be great!

• This should move you forward:-

Code:
```<div id = "results"></div>

<script type = "text/javascript">

var ids = new Array();
var string = "";
for (var i = 0; i <10; i++) {
ids[i] = i+1;
string = string + " " + ids[i];
}
document.getElementById("results").innerHTML = string;

</script>```
Note that the index of an array starts at 0, so here you need to make the 0th value = 1 by ids[i] = i+1;

A variant would be:-

Code:
```<script type = "text/javascript">

var ids = new Array();
var string = "";
for (var i = 0; i <=10; i++) {
ids[i] = i;
if (i > 0) {
string = string + " " + ids[i];
}
}
document.getElementById("results").innerHTML = string;

</script>```
“A man ceases to be a beginner in any given science and becomes a master in that science when he has learned that he is going to be a beginner all his life.” Robin G. Collingwood (English Philosopher, 1889-1943)

• ## The Following 2 Users Say Thank You to Philip M For This Useful Post:

icklechurch (03-20-2009), Mary U (03-21-2009)

• Brilliant, worked perfectly - thanks!

• This is great, Philip. I was having trouble with something similar, and as usual you make it seem so simple.

Mary

• Originally Posted by Mary U
This is great, Philip. I was having trouble with something similar, and as usual you make it seem so simple.

Mary
How kind!

"If you can't explain it simply, you don't understand it well enough”
“Everything should be as simple as it is, but not simpler.”

- both quotes Albert Einstein (German born American Physicist who developed the special and general theories of relativity. Nobel Prize for Physics in 1921. 1879-1955)

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•