tags:

views:

640

answers:

3

From the Mozilla Dev Site:

[1,4,9].map(Math.sqrt)

will yield:

[1,2,3]

Why then does this:

['1','2','3'].map(parseInt)

yield this:

[1, NaN, NaN]

I have tested in Firefox 3.0.1 and Chrome 0.3 and just as a disclaimer, I know this is not cross-browser functionality. (No IE)

[edit] I found out that the following will accomplish the desired effect. However, it still doesn't explain the errant behavior of parseInt.

['1','2','3'].map(function(i){return +i;}) // returns [1,2,3]
+1  A: 

I'm going to wager that it's something funky going on with the parseInt's 2nd parameter, the radix. Why it is breaking with the use of Array.map and not when you call it directly, I do not know.

//  Works fine
parseInt( 4 );
parseInt( 9 );

//  Breaks!  Why?
[1,4,9].map( parseInt );

//  Fixes the problem
[1,4,9].map( function( num ){ return parseInt( num, 10 ) } );
Peter Bailey
parseInt only assumes octal if the supplied string starts with a 0 character.
Alnitak
Oh ya... that's right. It tries to "guess" the radix based on the input. Sorry about that.
Peter Bailey
A: 

Try this:

['1','2','3'].map(parseInt())

parseInt() is a function.

m =  ['1','2','3'].map(parseInt())
alert(m[2]) >> 3
Diodeus
Thats wrong ! parseInt() won't work..
Vijay Dev
The argument for Array.map() has to be a function callback. This will not only not work, but it will throw an error at runtime.
Peter Bailey
var m = ['1','2','3'].map(parseInt());alert(m[2]); >> 3Works for me.
Diodeus
dunno how that works for you...it throws an error in both FF and Safari :O
shyam
+22  A: 

The callback function in Array.map has three parameters:

From the same Mozilla page that you linked to: "callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed." (https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map)

So if you call a function which actually expects two arguments, the second argument will be the index of the element.

In this case, you ended up calling parseInt with radix 0, 1 and 2 in turn. The first is the same as not supplying the parameter, so it defaulted to base 10. Base 1 is an impossible number base, and 3 is not a valid number in base 2.

Alnitak
Nice detail, Alnitak! This definitely corroborates my findings. Thanks for this response. Voted up!
Peter Bailey