Strange behavior for Map, parseInt

JavascriptFunctional Programming

Javascript Problem Overview


> Possible Duplicate:
> javascript - Array.map and parseInt

I saw this example of strange JavaScript behavior on twitter

['10','10','10','10','10'].map(parseInt)

evaluates to

[10, NaN, 2, 3, 4]

could somebody explain this behavior? I verified it in chrome and firebug

['10','10','10','10','10'].map(function(x){return parseInt(x);})

correctly returns an array of 10s as integers. Is this an improper use of map(), a bug with parseInt, or something else?

Javascript Solutions


Solution 1 - Javascript

parseInt receives two arguments: string and radix:

> var intValue = parseInt(string[, radix]);

while map handler's second argument is index:

> ... callback is invoked with three arguments: the value of the element, > the index of the element, and the Array object being traversed.

Solution 2 - Javascript

parseInt uses the first two arguments being passed in by map, and uses the second argument to specify the radix.

Here's what's happening in your code:

parseInt('10', 0) // 10
parseInt('10', 1) // NaN
parseInt('10', 2) // 2
parseInt('10', 3) // 3
parseInt('10', 4) // 4

Here's a link to MDN on parseInt: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt.

Solution 3 - Javascript

From MDN:

> callback is invoked with three arguments: the value of the element, > the index of the element, and the Array object being traversed.

parseInt() takes two arguments. The value and the radix. That means that the parseInt() function is being called with unintended parameters.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBen McCormickView Question on Stackoverflow
Solution 1 - JavascriptVisioNView Answer on Stackoverflow
Solution 2 - JavascriptJoseph SilberView Answer on Stackoverflow
Solution 3 - JavascriptJustin NiessnerView Answer on Stackoverflow