Javascript,while循环返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32170943/
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, while loop return
提问by Andy Li
var i = 0;
while(i < 100){
return "The number is " + i;
i++;
}
What is wrong with my return statement? Why can I return a string plus a variable?
我的退货声明有什么问题?为什么我可以返回一个字符串加上一个变量?
采纳答案by Sailesh Babu Doppalapudi
return
means end of function and return some value. Any statements after return statement will not be executed and the execution of a function will terminate at return statement. So, return
in your case will make the loop to execute only one and terminate it.
return
意味着函数结束并返回一些值。return 语句之后的任何语句都不会被执行,函数的执行将在 return 语句处终止。因此,return
在您的情况下,将使循环仅执行一个并终止它。
回答by reidm
I'm not exactly sure what you want to do with this text, but return
will take you out of the function. If you want to display this text, you could use <div id="demo">
and then use the function to create text inside of it like this:
我不确定你想用这个文本做什么,但return
会带你离开这个函数。如果要显示此文本,可以使用<div id="demo">
然后使用该函数在其中创建文本,如下所示:
var i = 0;
while(i < 100){
document.getElementById("demo").innerHTML += "<p>The number is " + i + "</p>";
i++;
}
回答by Srinivasulu Rao
First of all your code should be inside a function. Secondly the return statement which u have written inside the for loop will execute the result only once and it will come out of the entire function.
首先,你的代码应该在一个函数内。其次,您在 for 循环中编写的 return 语句只会执行一次结果,并且它会从整个函数中出来。