jQuery in Action
Manipulating JavaScript objects and collections
173
Let's look at a trivial example that shows the
$.map()
function in action.
var oneBased = $.map([0,1,2,3,4],function(value){return value+1;});
This statement converts an array of values, a zero-based set of indexes to a corre-
sponding array of one-based indexes.
sponding array of one-based indexes.
As with
$.grep()
, for such simple expressions, we can pass a string that repre-
sents the expression to make the statement more compact. The function gener-
ated on our behalf in such cases is passed the value as a parameter named
ated on our behalf in such cases is passed the value as a parameter named
a
(unlike
$.grep()
, the index isn't passed to auto-generated functions). We can
rewrite our example as
var oneBased = $.map([0,1,2,3,4],'a+1');
Another important behavior to note is that if the function returns either
null
or
undefined
, the result isn't collected. In such cases, the resulting array will be
smaller in length than the original, and one-to-one correspondence between
items by order is lost.
items by order is lost.
Let's look at a slightly more involved example. Imagine that we have an array
of strings, perhaps collected from form fields, that are expected to represent
numeric values and that we want to convert this array to an array of corresponding
numeric values and that we want to convert this array to an array of corresponding
Number
instances. Because there's no guarantee against the presence of an invalid
numeric string, we need to take some precautions. Consider the following code:
Function syntax: $.map
$.map(array,callback)
Iterates through the passed array, invoking the callback function for each array item and col-
lecting the return values of the function invocations in a new array.
lecting the return values of the function invocations in a new array.
Parameters
array
(Array) The array whose values are to be transformed to values in the new
array.
array.
callback
(Function|String) A function whose return values are collected in the new array
returned as the result of a call to the $.map() function.
This function is passed two parameters: the current data value and the index
of that value within the original array.
A string can also be passed that's converted into the callback function. See
the following discussion for details.
returned as the result of a call to the $.map() function.
This function is passed two parameters: the current data value and the index
of that value within the original array.
A string can also be passed that's converted into the callback function. See
the following discussion for details.
Returns
The wrapped set.
The wrapped set.