javascript 如何在javascript中返回到for循环的顶部

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

how to return to top of for loop in javascript

javascriptfor-loopreturn

提问by Darcy

Maybe this is a dumb question but is there a way to return to the top of a loop?

也许这是一个愚蠢的问题,但有没有办法返回到循环的顶部?

Example:

例子:

for(var i = 0; i < 5; i++) {

    if(i == 3)
        return;

    alert(i);
}

What you'd expect in other languages is that the alert would trigger 4 times like so:

您期望在其他语言中警报将触发 4 次,如下所示:

alert(0); alert(1); alert(2); alert(4);

警报(0);警报(1);警报(2);警报(4);

but instead, the function is exited immediately when i is 3. What gives?

但是,当 i 为 3 时,该函数立即退出。什么给出了?

回答by user113716

Use continueinstead of return.

使用continue代替return

Example:http://jsfiddle.net/TYLgJ/

示例:http : //jsfiddle.net/TYLgJ/

for(var i = 0; i < 5; i++) {

    if(i == 3)
        continue;

    alert(i);
}

If you wanted to completely halt the loop at that point, you would use breakinstead of return. The returnstatement is used to return a value from a function that is being executed.

如果您想在那时完全停止循环,您可以使用break代替return。该return语句用于从正在执行的函数中返回一个值。

EDIT:Documentation links provided by @epascarellothe comments below.

编辑:@epascarello提供的文档链接下面的评论。

回答by Sir Robert

For what it's worth, you can also label them:

对于它的价值,您还可以标记它们:

OUTER_LOOP: for (var o = 0; o < 3; o++) {
  INNER_LOOP: for (var i = 0; i < 3; i++) {
    if (o && i) {
      continue OUTER_LOOP;
    }
    console.info(o, ':', i);
  }
}

outputs:

输出:

0 : 0
0 : 1
0 : 2
1 : 0
2 : 0