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;
}
}
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With