How can I get 1 to 10 to show by fixing this code??
<script type="text/javascript">
var count = 0;
var numbers = new Array(10);
while (count <=10) {
numbers[count] = count;
++count;
}
count = 0;
while (count <=10) {
document.write(numbers[count] + 1 + "<br />");
+count();
}
</script>
i am new to this, any help would be much appreciated
-
What's the behavior right now? I have an idea of what to do but I'd like to know if my expected behavior is occurring.Purag– Purag2012年02月23日 03:01:45 +00:00Commented Feb 23, 2012 at 3:01
2 Answers 2
The main problem is this line:
+count();
This is a syntax error since you don't have a function called count, so execution simply stops as soon as it reaches that line. Replace it with:
++count;
(As done in the previous while loop.)
The second problem is that your loops are running from 0 to 10 inclusive, so you end up with 11 iterations. Change <= 10 to < 10.
Having said that, the whole thing seems a bit pointless. You create an array where item 0 holds the value 0, item 1 holds the value 1, etc., and then you print those values out? Why bother with the array at all? There's no point looking up the item at any particular array index if you already know in advance the value will be the same as the index.
If all you want is to display the numbers 1 through 10 then this will work:
for (var i=1; i <= 10; i++)
document.write(i + "<br />");
Comments
this will suffice:
var count = 0;
while (count <=9) {
document.write(numbers[count] + 1 + "<br />");
count++;
}