1

xs = ['10','10','10'] [ '10', '10', '10' ]

xs.map(parseInt) [ 10, NaN, 2 ] xs.map(parseFloat) [ 10, 10, 10 ]

why is the result 10,nan,2 for first one? why the second one is right?

BufBills
  • 8,005
  • 12
  • 48
  • 90

1 Answers1

3

.map() passes multiple arguments to its callback as in callback(element, index, array).

parseInt() uses that 2nd argument index that .map() passes as the radix distorting its result.

parseFloat(), on the other hand, only expects one argument so it works as expected.


If you pass instead a callback function, you can avoid that issue because then you control how parseInt() is called:

xs.map(item => parseInt(item, 10));
jfriend00
  • 683,504
  • 96
  • 985
  • 979