The map()
function is the ringleader of the bunch. It simply applies the callback function on each item in the array.
Syntax: arr.map(callback [, thisArg]);
Parameters:
callback()
: This function produces an element for the new array, receiving these arguments:currentValue
: This argument gives the current element being processed in the arrayindex
: This argument gives the index of the current element in the arrayarray
: This argument gives the array being processedthisArg()
: This function is optional. The value is used as this
when executing callback
.Examples:
var integers = [1,-0,9,-8,3], numbers = [1,2,3,4], str = 'hello world how ya doing?'; // map integers to their absolute values console.log(integers.map(Math.abs)); // multiply an array of numbers by their position in the array console.log(numbers.map(function(x, i){return x*i}) ); // Capitalize every other word in a string. console.log(str.split(' ').map(function(s, i){ if (i%2 == 0) { return s.toUpperCase(); } else { return s; } }) );
While the Array.prototype.map
method is a standard method for the Array object in JavaScript, it can be easily extended to your custom objects as well.
MyObject.prototype.map = function(f) { return new MyObject(f(this.value)); };