O'Reilly logo

Prototype and Scriptaculous: Taking the Pain out of JavaScript by Chris Angus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required