jQuery in Action
174
CHAPTER 6
jQuery utility functions
var strings = ['1','2','3','4','S','6'];
var values = $.map(strings,function(value){
var result = new Number(value);
return isNaN(result) ? null : result;
});
We start with an array of string values, each of which is expected to represent a
numeric value. But a typo (or perhaps user entry error) resulted in S instead of
the expected 5. Our code handles this case by checking the
numeric value. But a typo (or perhaps user entry error) resulted in S instead of
the expected 5. Our code handles this case by checking the
Number
instance cre-
ated by the constructor to see if the conversion from string to numeric was suc-
cessful or not. If the conversion fails, the value returned will be the constant
cessful or not. If the conversion fails, the value returned will be the constant
Number.NaN
. But the funny thing about
Number.NaN
is that by definition, it doesn't
equal anything else, including itself! Therefore the value of the expression
Num-
ber.NaN==Number.NaN
is
false
!
Because we can't use a comparison operator to test for
NaN
(which stands for
Not a Number, by the way), JavaScript provides the
isNaN()
method, which we
employ to test the result of the string-to-numeric conversion.
In this example, we return
null
in the case of failure, ensuring that the result-
ing array contains only the valid numeric values with any error values elided. If
we want to collect all the values, we can allow the transformation function to
return
we want to collect all the values, we can allow the transformation function to
return
Number.NaN
for bad values.
Another useful behavior of
$.map()
is that it gracefully handles the case where
an array is returned from the transformation function, merging the returned
value into the resulting array. Consider the following statement:
value into the resulting array. Consider the following statement:
var characters = $.map(
['this','that','other thing'],
function(value){return value.split('');}
);
This statement transforms an array of strings into an array of all of the characters
that make up the strings. After execution, the value of the variable
that make up the strings. After execution, the value of the variable
characters
is
as follows:
['t','h','i','s','t','h','a','t','o','t','h','e','r','','t','h',
'i','n','g']
This is accomplished by use of the
String.split()
method, which returns an
array of the string's characters when passed an empty string as its delimiter. This
array is returned as the result of the transformation function and is merged into
the resultant array.
array is returned as the result of the transformation function and is merged into
the resultant array.