A small strange behavior of map with parseInt in JavaScript

24 views Asked by At

I want to convert a string array to int array using map and parseInt function, but I find a interesting thing is ['2023', '12', '0'].map(parseInt) returns [2023, NaN, 0].

I have to rewrite to ['2023', '12', '0'].map(elem=> parseInt(elem)).

From the docs of parseInt, this function accepts one or two arguments. Maybe it's the root case.

Update: I found it's duplicated with Strange behavior for Map, parseInt and map + parseInt - strange results.

See more detailed explanation there.

.map calls parseInt() with three parameters - the value, the array index, and the array itself.

The index parameter gets treated as the radix:

parseInt('2023', 0, ['2023', '12', '0']); // OK - gives 2023, 0 radix here is become 10 because '2023', see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#description
parseInt('12', 1, ['2023', '12', '0']); // FAIL - gives NaN, 1 isn't a legal radix
parseInt('0', 2, ['2023', '12', '0']); // OK - gives 0 in base 2 
0

There are 0 answers