g(..).map(callbackFn, [thisObject])

Returns a new array, where each element in the new array a direct one-to-one mapping of each element from the Gimme Object's underlying array (but which has been modified by the specified callback function). Optionally, you may specifying the object to be used as the "this" object in the callback by supplying the second parameter.

Returns: A new array whose elements are generated from the specified mapping/callback function.
  • callbackFn, required: A function reference that will be invoked for each element in the Gimme Object's internal array.
  • thisObject, optional: An object to be used as the "this" object from within the callbackFn.

// From a array of <divs>, return an array <spans>whose innerHTML comes from the corresponding <div>
var spans = g('div.transformMe').map(function(div, idx)
	var s = document.createElement('span');
	s.innerHTML = div.innerHTML;
	return s;

// A more concrete example, using plain old numbers
var multiplesOfFive = g([1, 2, 3, 4, 5]).map(function(num, idx)
	return num * 5;
alert(multiplesOfFive);				// [ 5, 10, 15, 20, 25 ]

Related Information:
  • The callbackFn is expected to return some result and should always end with a return statement. If it does not, the new array will be filled with undefined values.
  • The object, elem (or num or div or whatever it may be), and the loop index, idx, are automatically passed into the callbackFn.
  • Inside the callbackFn, the "this" is whatever object you passed into the .forEach(..) function as the 2nd parameter. If this parameter was omitted, then "this" will refer to the window object.

Last edited Nov 13, 2007 at 9:06 PM by sstchur, version 2


No comments yet.