0

I am tring to use parseInt in a map, but some strange behavor happened, here is code:

["1","2"].map(parseInt)

the result is:

[1, NaN]

but when I wrap the parseInt function:

["1","2"].map(function(n){ return parseInt(n)})

it works fine, the result is:

[1, 2]

why?

Yang
  • 406
  • 3
  • 9
  • 1
    I suspect it's related to `parseInt` taking two input parameters. You can see the same behavior by modifying your wrapper function to take in `(n, m)`. On the other hand, `parseFloat` works as expected, and it only takes one parameter. – Chris Hayes Dec 26 '13 at 02:10
  • This is a dup of a dup of a dup of a dup... http://stackoverflow.com/questions/262427/javascript-arraymap-and-parseint – elclanrs Dec 26 '13 at 02:11
  • You can use `["1","2"].map(Number)` – PSL Dec 26 '13 at 02:11
  • 1
    Actually, in addition to being a dupe, this same situation is called out in the MDN documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Tricky_use_case – Chris Hayes Dec 26 '13 at 02:12

0 Answers0