tags:

views:

138

answers:

2

Possible Duplicate:
JavaScript - Array.map and parseInt

I've run into something strange:

["1", "3", "5"].map(parseInt) returns [1, NaN, NaN], but ["1", "3", "5"].map(function(str){ return parseInt(str);}) returns the expected [1, 3, 5].

Why?

I've only tested this in Google Chrome 7.


Edit: Thanks for all the answers. Now I know what happens. With the help of the explanations below I figured out this would work:

parseInt2 = function(str){ return parseInt(str) }
["1", "3", "5"].map(parseInt2);

This results in the expected [1, 3, 5] array. All these extra params (i.e. index in map) is not always good, it seems.

+3  A: 

The callback of Array.map can receive up to three arguments: the value of the element, the index of the element, and the Array object being traversed. Therefore parseInt() is being passed the second argument, the radix argument. The radix of 0, 1, and 2 is producing the unexpected results:

["1", "3", "5"].map(function (a, b) {
   console.log(a + ', ' + b);
   console.log(parseInt(a, b));
});

Returns:

1, 0
1

3, 1
NaN

5, 2
NaN
Daniel Vassallo
Nice explanation! Yep, that's it.
Johan Jonasson
+7  A: 

http://stackoverflow.com/questions/262427/javscript-array-map-and-parseint

Fabrizio Calderan
wow, 6 upvotes just for pointing at someone else's question?!
Alnitak