views:

348

answers:

3

This works fine:

["655971", "2343", "343"].map(function(x) { return parseInt(x) }) // [655971, 2343, 343]

But this doesnt:

["655971", "2343", "343"].map(parseInt) // [655971, NaN, NaN]

The same happens for Array.filter()

What am I missing here?

+1  A: 

Array.Filter takes a function that returns information whether or not the item to evaluated satisfies the condition. IsNumeric will work for what you want.

http://www.hunlock.com/blogs/Mastering_Javascript_Arrays

Kevin
+4  A: 

The problem is that map expects that the callback should be a function that accepts three arguments, callbackfn(value, index, array).

The second argument is clashing with the radix argument of the parseInt(string, radix) function.

Map calls parseInt like this for each element:

parseInt("655971",0); // 655971
parseInt("2343", 1);  // NaN
parseInt("343", 2);   // NaN

The first one works because if radix is undefined or 0, it is assumed to be 10.

CMS
wish I could give both you guys the answer but had to choose the first. :)
bucabay
+6  A: 

It's because map passes more arguments than just the array item into the callback function. You get:

callback(item, index, array)

Normally your function would just ignore the arguments it didn't need. But parseInt accepts an optional second parameter:

parseInt(string, base)

for the first call, base is the index 0. That works okay because ECMAScript defines that base=0 is the same as omitting the argument, and consequently allows decimal, octal or hex (using decimal in this case).

For the second and third items, base is 1 or 2. It tries to parse the number as base-1 (which doesn't exist) or base-2 (binary). Since the first number in the string is a digit that doesn't exist in those bases, you get a NaN.

In general, parseInt without a base is pretty questionable anyway, so you probably want:

["655971", "2343", "343"].map(function(x) { return parseInt(x, 10) })
bobince
Another option (although with different semantics) in some cases is to use the `Number` function. When called without `new` it converts its argument to a number, similar to the unary `+` operator.
Matthew Crumley
(Yep... `Number` or `+` are fine, though they wont ensure it's an integer number.)
bobince
how would us use + ?
bucabay
`.map(function(x) { return +x; }`. You could possibly also do it with `Number` as simply `.map(Number)`, since the `Number` function doesn't take any extra parameters like `parseInt` does. However that's assuming that ECMAScript will never add any more optional parameters (is this a safe assumption? hmm). Incidentally both `Number` and `+` will accept a hex string (but not, thankfully, accidental octals).
bobince