3.5. Enumerable Objects and Iterator Functions

Prototype brings higher-order functions to mainstream JavaScript in the form of enumerable objects. The Enumeration interface represents a collection objects and exposes a set of functions that allow the manipulation of these objects using iterator functions.

An iterator function is a normal JavaScript function of the form:

var iterator = function(value,index)
{
       ...
}

where the arguments to this function represent a value from the collection and the index that the value is at within the collection. Armed with an iterator function, we may make use of the functions on Enumerable.

each Calls the iterator on each element
all Returns true if all iterators return true
any Returns true if any iterator returns true
collect Maps the iterator across the collection, returning a collection of results in the same order
detect Returns first element for which the iterator returns true
entries Returns an array of elements
find Same as detect
findAll Returns all elements for which the iterator returns true
grep Returns all elements for which a regular expression matches
include Returns true if a given object is in the collection
inject Collapses the collection into a value using the iterator with an additional initial accumulating parameter as an accumulator.
invoke Invokes a member function (passing in arguments) on each element in the collection
map Same as collect
max Returns the maximum element
member Same as include ...

Get Prototype and Scriptaculous: Taking the Pain out of JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.