打破内在的foreach循环 [英] Breaking out of an inner foreach loop

查看:65
本文介绍了打破内在的foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用JavaScript / jQuery打破内部foreach循环。

I am trying to break out of an inner foreach loop using JavaScript/jQuery.

result.history.forEach(function(item) {
    loop2:
    item.forEach(function(innerItem) {
        console.log(innerItem);
        break loop2;
    });
}); 

这导致错误'Unidentified label loop2'。它似乎是在循环之前,这是其他问题所说的问题。

This is resulting in the error 'Unidentified label loop2'. it appears to be right before the loop which was what other questions were saying was the issue.

我做错了什么以及如何解决?

What am I doing wrong and how do I fix it?

编辑:正确,foreach循环不能以这种方式中断,但是常规for循环可以。这是有效的:

Correct, the foreach loop cant break in this way but a regular for loop can. This is working:

                        result.history.forEach(function(item) {
                            loop2:
                            for (var i = 0; i < item.length; i++) {
                                var innerItem = item[i];
                                console.log(innerItem);
                                break loop2;
                            }
                        });


推荐答案

如果你需要能够打破迭代,使用 .every()而不是 .forEach()

If you need to be able to break an iteration, use .every() instead of .forEach():

someArray.every(function(element) {
  if (timeToStop(element)) // or whatever
    return false;
  // do stuff
  // ...
  return true; // keep iterating
});

您可以翻转 true / false 逻辑并使用 .some()代替;相同的基本想法。

You could flip the true/false logic and use .some() instead; same basic idea.

这篇关于打破内在的foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆