I think it's worth mentioning how Underscore _.each () works internally. _.each (list, iteratee) checks if the passed list is an array object or an object.
In the case where the list is an array, iteratee arguments will be a list item and an index, as in the following example:
var a = ['I', 'like', 'pancakes', 'a', 'lot', '.']; _.each( a, function(v, k) { console.log( k + " " + v); }); 0 I 1 like 2 pancakes 3 a 4 lot 5 .
On the other hand, if list is an object, iteratee will accept a list item and a key:
var o = {name: 'mike', lastname: 'doe', age: 21}; _.each( o, function(v, k) { console.log( k + " " + v); }); name mike lastname doe age 21
For reference, this is the code _.each () from Underscore.js 1.8.3
_.each = _.forEach = function(obj, iteratee, context) { iteratee = optimizeCb(iteratee, context); var i, length; if (isArrayLike(obj)) { for (i = 0, length = obj.length; i < length; i++) { iteratee(obj[i], i, obj); } } else { var keys = _.keys(obj); for (i = 0, length = keys.length; i < length; i++) { iteratee(obj[keys[i]], keys[i], obj); } } return obj; };
mszymulanski Dec 09 '15 at 16:44 2015-12-09 16:44
source share