back to Overview

.each()

Invokes the given function once for each item in the list.
Available in all modules.

Syntax Variants

list.each(callback)
list.each(callback, ctx)
_.each(list, callback)
_.each(list, callback, ctx)

Parameters

list
a list to iterate. Can be an array, a Minified list or any other array-like structure with length property.
callback
The callback function(item, index) to invoke for each list element.
item
The current list element.
index
The second the zero-based index of the current element.
this
The given context if not null. Otherwise the list.
The callback's return value will be ignored.
ctx (optional)
a context to pass to the callback as 'this'. Only supported in UTIL module.
(return value)
the list

Description

Invokes the given function once for each item in the list. The function will be called with the item as first parameter and the zero-based index as second. Unlike JavaScript's built-in forEach() it will be invoked for each item in the list, even if it is undefined.

Example

Creates the sum of all list entries.

var sum = 0;
_(17, 4, 22).each(function(item, index) {
    sum += item;
});

Example

The previous example with a native array:

var sum = 0;
_.each([17, 4, 22], function(item, index) {
    sum += item;
});

Example

This goes through all h2 elements of the class 'section' on a web page and changes their content:

$('h2.section').each(function(item, index) {
    item.innerHTML = 'Section ' + index + ': ' + item.innerHTML;
});

See also..

  • per() works like each(), but wraps the list elements in a list.
  • find() can be used instead of each() if you need to abort the loop.
  • eachObj() iterates through the properties of an object.

Comments

comments powered by Disqus

back to Overview

Functions