Underscore.JS - each method



Syntax

_.each(list, iteratee, [context]) 

each method iterates over a given list of element, call the iteratee function which is bound to context object, if passed. Iteratee is called with three parameters: (element, index, list). In case of JavaScript object, iteratee's object will be (value, key, list). Returns the list for chaining purpose.

Example

var _ = require('underscore');

var list = '';

//Example 1. access each number of array
_.each([1, 2, 3], function(x) { list += x + ' ' });
console.log(list);

list = ''

//Example 2. access each key-value of object
_.each({one: 1, two: 2, three: 3}, function(value, key) { list += key + ':' + value + ' ' });
console.log(list);

Save the above program in tester.js. Run the following command to execute this program.

Command

\>node tester.js

Output

1 2 3
one:1 two:2 three:3
underscorejs_iterating_collection.htm
Advertisements