Login Register

Array Iterators

Dojo provides various functions to Iteration over arrays, rather than the for() loop of traditional procedural languages. A callback function is specified and called for each element of an array.

For example, this will display three alerts, one for each of the specified words:

var colors = ["red", "white", "blue"];

dojo.lang.forEach(colors, alert);

This will return an array of the squares of the first five positive integers:

var integers = [1,2,3,4,5];

var squares = dojo.lang.map(integers, function(x){ return x*x; });

There are also functions:

  • dojo.lang.filter - filter out matching items from an array into a new array
  • dojo.lang.some - tests if given function returns true for any element in the array
  • dojo.lang.every - tests if function returns true for every array element

The iteration functions work on arrays, comma separated lists, or other array-like variables.