返回停止循环吗?
如果我有以下循环的
for (var i = 0; i < SomeArrayOfObject.length; i++) {
if (SomeArray[i].SomeValue === SomeCondition) {
var SomeVar = SomeArray[i].SomeProperty;
return SomeVar;
}
}
返回
语句停止函数的执行?
If I have the following for
loop
for (var i = 0; i < SomeArrayOfObject.length; i++) {
if (SomeArray[i].SomeValue === SomeCondition) {
var SomeVar = SomeArray[i].SomeProperty;
return SomeVar;
}
}
Does the return
statement stop the function's execution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
是的,只要函数的控制流量满足
返回
语句,函数总是会结束。下面的示例演示了
返回
语句如何结束函数的执行。注意:请参见其他答案关于
的特殊情况
try -catch -
最后
和此答案>回调具有其自己的功能范围,因此它不会突破包含的函数。Yes, functions always end whenever their control flow meets a
return
statement.The following example demonstrates how
return
statements end a function’s execution.Notes: See this other answer about the special case of
try
–catch
–finally
and this answer about how theforEach
callback has its own function scope, so it will not break out of the containing function.在大多数情况下(包括此),
返回
将立即退出。但是,如果返回是在中尝试
带有随附的最后
block block中的最后
始终执行并可以“覆盖”在
中返回
尝试。In most cases (including this one),
return
will exit immediately. However, if the return is in atry
block with an accompanyingfinally
block, thefinally
always executes and can "override" thereturn
in thetry
.此代码将在第一次迭代之后退出循环的第一次迭代:
以下代码将在条件下跳跃,并继续以循环的继续进行:
This code will exit the loop after the first iteration in a
for of
loop:the below code will jump on the condition and continue on a
for of
loop:返回
语句仅在函数内部时停止循环(即它同时终止循环和函数)。否则,您将获得此错误:要终止循环,您应该使用
break
。The
return
statement stops a loop only if it's inside the function (i.e. it terminates both the loop and the function). Otherwise, you will get this error:To terminate a loop you should use
break
.是的,一旦执行
返回
语句,整个函数将在当时退出。试想一下,如果不这样做并继续循环会发生什么,并每次执行该
返回
语句?当您考虑它时,它将返回值的含义无效。Yes, once the
return
statement is executed, the entire function is exited at that very point.Just imagine what would happen if it did not and continued looping, and executing that
return
statement each time? It would invalidate it's meaning of returning a value when you think about it.答案是肯定的,如果您编写返回语句,则控件会立即返回到呼叫者方法。
除了最终块,在返回语句之后将执行。
最后,如果您返回最终阻止,也可以覆盖您已返回的值。
-finally-retrife
catch
链接: try - :
:
维基百科:
The answer is yes, if you write return statement the controls goes back to to the caller method immediately.
With an exception of finally block, which gets executed after the return statement.
and finally can also override the value you have returned, if you return inside of finally block.
LINK: Try-catch-finally-return clarification
Return Statement definition as per:
Java Docs:
MSDN Documentation:
Wikipedia:
“返回”确实退出了该函数,但是如果要返回大量数据,则可以将其存储在数组中,然后将其返回,而不是试图在循环中返回每个数据1 x 1。
"return" does exit the function but if you want to return large sums of data, you can store it in an array and then return it instead of trying to returning each piece of data 1 by 1 in the loop.