转到 JavaScript forEach 循环中的“下一个”迭代

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

Go to "next" iteration in JavaScript forEach loop

javascriptforeach

提问by Don P

How do I go to the next iteration of a JavaScript Array.forEach()loop?

如何进入 JavaScriptArray.forEach()循环的下一次迭代?

For example:

例如:

var myArr = [1, 2, 3, 4];

myArr.forEach(function(elem){
  if (elem === 3) {
    // Go to "next" iteration. Or "continue" to next iteration...
  }

  console.log(elem);
});

MDN docsonly mention breaking out of the loop entirely, not moving to next iteration.

MDN 文档只提到完全跳出循环,没有进入下一次迭代。

回答by rid

You can simply returnif you want to skip the current iteration.

return如果您想跳过当前迭代,您可以简单地。

Since you're in a function, if you returnbefore doing anything else, then you have effectively skipped execution of the code below the returnstatement.

因为你在一个函数中,如果你return在做任何其他事情之前,那么你已经有效地跳过了return语句下面的代码的执行。

回答by Christoffer Karlsson

JavaScript's forEach works a bit different from how one might be used to from other languages for each loops. If reading on the MDN, it says that a functionis executed for each of the elements in the array, in ascending order. To continue to the next element, that is, run the next function, you can simply return the current function without having it do any computation.

JavaScript 的 forEach 的工作方式与其他语言的每个循环的使用方式略有不同。如果在MDN上阅读,它会说对数组中的每个元素按升序执行一个函数。要继续下一个元素,即运行下一个函数,您可以简单地返回当前函数,而无需对其进行任何计算。

Adding a return and it will go to the next run of the loop:

添加一个 return ,它将进入循环的下一次运行:

var myArr = [1,2,3,4];

myArr.forEach(function(elem){
  if (elem === 3) {
    return;
  }

  console.log(elem);
});

Output: 1, 2, 4

输出:1、2、4

回答by dimshik

just return true inside your if statement

只需在 if 语句中返回 true

var myArr = [1,2,3,4];

myArr.forEach(function(elem){
  if (elem === 3) {

      return true;

    // Go to "next" iteration. Or "continue" to next iteration...
  }

  console.log(elem);
});