Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

javascript - Breaking out of an inner foreach loop

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;
    });
}); 

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?

Edit: 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;
                            }
                        });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
});

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...