0
(['1','2','3']).map(n => parseInt(n));

will return expect result [1,2,3]

But:

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

returns [1, NaN, NaN].

Where is wrong?

Freewind
  • 193,756
  • 157
  • 432
  • 708
  • @NagaSaiA – Check the result of `z` – Rayon Jul 30 '16 at 07:29
  • Always use the explicit version of `map` to avoid unexpected behavior: `[...].map(x => f(x))`. –  Jul 30 '16 at 07:36
  • Does this answer your question? [Why does parseInt yield NaN with Array#map?](https://stackoverflow.com/questions/262427/why-does-parseint-yield-nan-with-arraymap) – Ivar Aug 05 '21 at 15:16

1 Answers1

4

As Array#map callback has 3 arguments, second argument is index which is causing this result. No matter what function you pass as callback, this arguments are passed as parameters for that function.

Second argument for parseInt is radix hence parseInt('2',1) and parseInt('3',2) is NaN

Execution flow will be:

console.log((['1', '2', '3']).map(function(currenValue, index, array) {
  return parseInt(currenValue, index, array);
}));

I will suggest you to go with the Number

console.log((['1', '2', '3']).map(Number));
Rayon
  • 36,219
  • 4
  • 49
  • 76
  • 1
    There are some subtle details about `parseInt` here. If you pass a radix of `0` it appears that `parseInt` treat it as base-10 so `0` is the same as `10` or the default. It also appears that radix `1` always return NaN even though base-1 numbers exist (often called a "tally") - so `parseInt` does not support base-1 numbers. Finally at least on Chrome `parseInt` does not support radix higher than 36 - it will always return NaN – slebetman Aug 05 '21 at 15:34