How do you 'continue' like with for loops when iterating with a closure in javascript
Using underscore.js is there a way to breakout of the each if a certain condition is met?
_.each([1,2,3开发者_开发百科], function(value) {
if (value == 2) {
// continue 2
return false;
}
});
I'm sure returning false did the trick in prototype.js
Looks like you should return breaker
, which isn't in scope it seems. So, without modifying _
, you can't easily break out of iteration. The ===
there will ensure that returning {}
won't cause the loop to break; you need a reference to breaker
, which you don't have.
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects implementing `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (_.isNumber(obj.length)) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
I'm not sure if you can actually stop the loop but you could use a boolean to stop the code in the loop from executing:
var keep_going = true;
_.each([1,2,3], function(value) {
if(keep_going){
if (value == 2) {
// continue 2
keep_going = false;
}
}
});
You can't. As Stefan posted above, if your browser does not support Array.prototype.forEach (which is a long shot these days), you could return breaker
-- if you had access to it. But unfortunately, you don't, because breaker
is defined as {}
in a closure in the underscore.js library.
Unfortunately, the behavior of JavaScript is that two objects are not equal to one another unless they are the exact same object. Therefore, ({}) === ({})
is false -- and so returning {}
from your function will not pass an equality check with the internal breaker
variable.
So, you can't break out of loops like this without roundabout methods like posted above. And, according to the MDC, there is no way to break the native forEach that is used.
It may very well be that .each
does not support skipping.
You can do it the roundabout way:
var skip = false;
_.each([1,2,3], function(value) {
if (true === skip) {
return;
}
if (value == 2) {
skip = true;
return false;
}
});
But I'm sure there is a better function for it.
精彩评论