Here is my code. I am expecting "the number is 1, the number is 2..." to be out putted up to 5 but all that is outputted is the number is 0 not sure why.
<script>
var i=0;
function test(){
for(i=0;i<=5;i++){
return "the number is" + i;
}
}
</script>
<script>
document.write(test());
</script>
Here is my code. I am expecting "the number is 1, the number is 2..." to be out putted up to 5 but all that is outputted is the number is 0 not sure why.
<script>
var i=0;
function test(){
for(i=0;i<=5;i++){
return "the number is" + i;
}
}
</script>
<script>
document.write(test());
</script>
Share
Improve this question
asked Feb 18, 2012 at 4:59
Cool Guy YoCool Guy Yo
6,11015 gold badges60 silver badges90 bronze badges
2 Answers
Reset to default 5return "the number is" + i;
It (the 'point' of script execution) returns back from the function with the first loop at i = 0
Write it as http://jsfiddle/hNWrg/
function test(){
var out = '';
for(var i=0;i<=5;i++){
out += "the number is" + i + "<br>";
}
return out;
}
your function is returning 0 the first time through the loop :-) try this:
<script>
var i=0;
function test(){
for(i=0;i<=5;i++){
document.write("the number is" + i);
}
}
</script>
<script>
test();
</script>