2

Can someone explain why this has the unexpected result:

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

which returns [1, NaN, NaN] instead of [1, 2, 3]?

I can make it work by forcing a single-argument function:

["1", "2", "3"].map(function(s) {return parseInt(s);});

but I don't know what exactly went wrong in the first way.

Yan King Yin
  • 1,189
  • 1
  • 10
  • 25

3 Answers3

2

As others mentioned, the problem is due to the 2nd argument.

Comments from MDN:

// parseInt is often used with one argument, but takes two. The second being the radix
// To the callback function, Array.prototype.map passes 3 arguments: the element, the index, the array
// The third argument is ignored by parseInt, but not the second one, hence the possible confusion.
// See the blog post for more details

But, with the use of bind, you can achieve the desired result:

var _parseInt = function(radix, number) {
  return parseInt(number, radix);
}
["1", "2", "3"].map(_parseInt.bind(this, 10));
1

this article describes your issue in its last sample, exactly the same what you are trying to do. However the blog article they refer to doesn't exist anymore.

array.map() and parseInt callback

A better answer cited from Stackoverflow:

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 
Community
  • 1
  • 1
Avinor
  • 846
  • 1
  • 8
  • 19
1

parseInt takes two arguments (the second being the radix), that's why this doesn't work. See the bottom of this MDN page for more information. Cited:

parseInt is often used with one argument, but takes two. The second being the radix To the callback function, Array.prototype.map passes 3 arguments: the element, the index, the array. The third argument is ignored by parseInt, but not the second one, hence the possible confusion.

KooiInc
  • 119,216
  • 31
  • 141
  • 177