Javascript return 会停止循环吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11714503/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:49:09  来源:igfitidea点击:

Does return stop a loop?

javascriptloopsreturn

提问by frenchie

Suppose I have a loop like this:

假设我有一个这样的循环:

for (var i = 0; i < SomeArrayOfObject.length; i++) {

  if (SomeArray[i].SomeValue === SomeCondition) {

     var SomeVar = SomeArray[i].SomeProperty;
     return SomeVar;
  }
}

Quick question: does the returnstop the execution of the loop in and of itself?

快速提问:是否会return停止循环本身的执行?

回答by Michael Berkowski

Yes, returnstops execution and exits the function. returnalways** exits its function immediately, with no further execution if it's inside a for loop.

是的,return停止执行并退出函数。returnalways** 立即退出它的函数,如果它在 for 循环内则不再执行。

It is easily verified for yourself:

自己很容易验证:

function returnMe() {
  for (var i=0; i<2; i++) {
    if (i === 1) return i;
  }
}

alert(returnMe());
// 1

** Notes: See this other answerabout the special case of try/catch/finallyand this answerabout how forEach loops has its own function scope will not break out of the containing function.

** 注意:请参阅有关特殊情况的其他答案try/catch/finally以及有关 forEach 循环如何拥有自己的函数范围的答案不会脱离包含函数。

回答by John Girata

In mostcases (including this one), returnwill exit immediately. However, if the return is in a tryblock with an accompanying finallyblock, the finallyalways executes and can "override" the returnin the try.

大多数情况下(包括这一种),return会立即退出。但是,如果返回的是一个try块加上一个finally块中,finally始终执行并能“覆盖”了returntry

function foo() {
    try {
        for (var i = 0; i < 10; i++) {
            if (i % 3 == 0) {
                return i; // This executes once
            }
        }
    } finally {
        return 42; // But this still executes
    }
}

console.log(foo()); // Prints 42

回答by Damjan Pavlica

The returnstatement stops a loop only if it's inside the function. Otherwise, you will get this error:

return仅当循环在函数内部时,该语句才会停止循环。否则,您将收到此错误:

Uncaught SyntaxError: Illegal return statement(…)

回答by PersianIronwood

This code will exit the loop after the first iteration in a for ofloop:

此代码将在循环中的第一次迭代后退出for of循环:

const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];
for (const iterator of objc) {
  if (iterator.name == 2) {
    return;
  }
  console.log(iterator.name);// 1
}

the below code will jump on the condition and continue on a for ofloop:

下面的代码将跳转到条件并继续for of循环:

const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];

for (const iterator of objc) {
  if (iterator.name == 2) {
    continue;
  }
  console.log(iterator.name); // 1  , 3
}

回答by Keldon Alleyne

Yes, once the returnstatement is executed, the entire function is exited at that very point.

是的,一旦return语句被执行,整个函数就会在那个时候退出。

Just imagine what would happen if it did not and continued looping, and executing that returnstatement each time? It would invalidate it's meaning of returning a value when you think about it.

试想一下,如果它不这样做并继续循环并return每次都执行该语句会发生什么?当您考虑它时,它会使返回值的含义无效。

回答by user1179299

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.

答案是肯定的,如果您编写 return 语句,则控件会立即返回到调用方方法。除了 finally 块,它在 return 语句之后执行。

and finally can also override the value you have returned, if you return inside of finally block. LINK: Try-catch-finally-return clarification

如果您在 finally 块内返回,并且 finally 也可以覆盖您返回的值。链接:Try-catch-finally-return 澄清

Return Statement definition as per:

返回语句定义如下:

Java Docs:

Java 文档:

a return statement can be used to branch out of a control flow block and exit the method

return 语句可用于分支出控制流块并退出该方法

MSDN Documentation:

MSDN 文档:

The return statement terminates the execution of a functionand returns control to the calling function. Execution resumes in the calling function at the point immediately following the call.

return 语句终止函数的执行并将控制权返回给调用函数。执行在调用函数中紧跟在调用之后的点处恢复。

Wikipedia:

维基百科:

A return statement causes execution to leave the current subroutine and resume at the point in the code immediately after where the subroutine was called, known as its return address. The return address is saved, usually on the process's call stack, as part of the operation of making the subroutine call. Return statements in many languages allow a function to specify a return value to be passed back to the code that called the function.

return 语句导致执行离开当前子例程,并在代码中调用子例程后立即恢复,称为返回地址。返回地址通常保存在进程的调用堆栈中,作为进行子例程调用的操作的一部分。许多语言中的 Return 语句允许函数指定要传递回调用该函数的代码的返回值。

回答by Brendon McBain

"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.

“return”确实退出了函数,但是如果你想返回大量数据,你可以将它存储在一个数组中,然后返回它,而不是试图在循环中 1 个 1 地返回每条数据。