icklechurch
03-20-2009, 10:32 AM
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! :)
Philip M
03-20-2009, 11:07 AM
This should move you forward:-
<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];
}
alert (ids);
alert (string);
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:-
<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];
}
}
alert (ids);
alert (string);
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)
icklechurch
03-20-2009, 12:09 PM
Brilliant, worked perfectly - thanks! :)
Mary U
03-20-2009, 11:31 PM
This is great, Philip. I was having trouble with something similar, and as usual you make it seem so simple.
Mary
Philip M
03-21-2009, 08:41 AM
This is great, Philip. I was having trouble with something similar, and as usual you make it seem so simple.
Mary
How kind! :o
"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)