Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 414
serby Avatar asked Jun 02 '11 18:06

serby


1 Answers

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;
        }
      }
    }
  };
like image 101
Stefan Kendall Avatar answered Oct 20 '22 09:10

Stefan Kendall