Introduction

Array extends the functionality of JavaScript's built-in Array object. I worked with Perl quite a bit before learning JavaScript. As a result, I found that I missed a few things from Perl. Specifically, I really wanted the functionality of "foreach" and the "map" function. This JavaScript file adds a close approximation to those Perl methods.

Reference

Methods

foreach(func);

foreach() loops through all of the members of the Array object. The function literal will be called once for each member of the array and will have the current member passed into as a parameter.

map(func);

map() functions very similarly to foreach; however, the results of each invocation of the function literal is appended to a resulting array. Once all members of the current Array object have been visited, an array of the results is returned from this method.

Example

The following example creates an array, increments each member by 1 (returning a new array), and then displays each member in an alert dialog, one member at a time.

var array1 = [1, 2, 3];
var array2;
// Add one to each member of array1
// A new array is returned
// The original array is not effected
array2 = array1.map(
function(elem) {
return elem + 1;
}
);
// Show each member of the array in an alert dialog box
array2.foreach(
function(elem) {
alert(elem)
}
);