3

I want it to parse to integers a String's array that had the id's from a selected html element, so I use this code:

var x = ["1", "2","3","4","5"];
var y = x.map(parseInt);

I was expecting:

[1,2,3,4,5]

But instead I get:

[1,NaN,NaN,NaN,NaN]

If I change it to this other ways it works as expected:

var z = x.map(function(item){return parseInt(item)});
var q = x.map(Number);

You can see it the same behavior on safari, chrome and firefox live here: jsfiddle.net: Error on Map(parseInt)

So my question is: Is this a bug or a feature?

Proteo5
  • 65
  • 4
  • There are two concerns with calling functions. What is being passed, and what is expected. The `.map()` passes 3 arguments to the callback, and the `parseInt` accepts two. JavaScript allows the mismatch, and so `parseInt` will just ignore the last one, and use the two it expects to receive. So if you look at the docs for both, you'll see what is passed and how they will be used, and then you'll see the problem. –  Dec 08 '17 at 23:02
  • 1
    @ibrahimmahrir That perfectly explain what I was asking for. Thanks. – Proteo5 Dec 08 '17 at 23:09
  • Thanks @rockstar this is one of the hidden things not very known. – Proteo5 Dec 08 '17 at 23:17

0 Answers0