Javascript, while loop return

眉间皱痕 提交于 2019-11-30 09:24:51

问题


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?


回答1:


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.




回答2:


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.




回答3:


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:

var i = 0;
while(i < 100){
    document.getElementById("demo").innerHTML += "<p>The number is " + i + "</p>";
    i++;
}

http://jsfiddle.net/rmerzbacher/fdu7aauz/



来源:https://stackoverflow.com/questions/32170943/javascript-while-loop-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!