javascript for 函数内的循环然后将其输出到页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9338719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript for loop inside a function then output it to the page
提问by Cool Guy Yo
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.
这是我的代码。我期待“数字是 1,数字是 2...”被输出到 5,但输出的只是数字是 0 不知道为什么。
<script>
var i=0;
function test(){
for(i=0;i<=5;i++){
return "the number is" + i;
}
}
</script>
<script>
document.write(test());
</script>
回答by Cheery
return "the number is" + i;
It (the 'point' of script execution) returns back from the function with the first loop at i = 0
return "the number is" + i;
它(脚本执行的“点”)从函数返回,第一个循环位于 i = 0
Write it as http://jsfiddle.net/hNWrg/
将其写为http://jsfiddle.net/hNWrg/
function test(){
var out = '';
for(var i=0;i<=5;i++){
out += "the number is" + i + "<br>";
}
return out;
}
回答by Justin Beckwith
your function is returning 0 the first time through the loop :-) try this:
您的函数第一次通过循环返回 0 :-) 试试这个:
<script>
var i=0;
function test(){
for(i=0;i<=5;i++){
document.write("the number is" + i);
}
}
</script>
<script>
test();
</script>