brad brad - 26 days ago 6
Javascript Question

javascript - Array#map and parseInt

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]

Answer

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."

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:

parseInt('1', 0); // OK - gives 1
parseInt('2', 1); // FAIL - 1 isn't a legal radix
parseInt('3', 2); // FAIL - 3 isn't legal in base 2