Iterates over a list of elements, yielding each in turn to an iterator function. Theiterator is bound to the context object, if one is passed. Each invocation of iteratoris called with three arguments: (element, index, list). If list is a JavaScript object, iterator's arguments will be (value, key, list). Delegates to the nativeforEach function if it exists.
遍历函数原色,产生一个迭代的方法。 别名forEach .可遍历数组和对象。
1 _.each([1, 2, 3], function(num){ alert(num); });2 => alerts each number in turn...3 _.each({one : 1, two : 2, three : 3}, function(num, key){ alert(num); });4 => alerts each number in turn...
源码
var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return; if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +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 (_.has(obj, key)) { if (iterator.call(context, obj[key], key, obj) === breaker) return; } } } };