GusOst GusOst - 7 months ago 23
Javascript Question

Applying parseInt on array yields weird result

Trying to run a simple javascript to parse single digit ints in a string as follows:

var s = "22123222222213123212322123213222";
var a = s.split("");
var b = a.map(parseInt);
console.log(b);
[2, NaN, 1, 2, 3, 2, 2, 2, 2, 2, 2, 2, 1, 3, 1, 2, 3, 2, 1, 2, 3, 2, 2, 1, 2, 3, 2, 1, 3, 2, 2, 2]


Why is there a NaN for element with index 1?

Fiddle in the console here:
https://jsfiddle.net/po6oy1ws/

EDIT

After getting the correct answer below I felt I had to lookup this "map(Number)" business. Turns out Mozilla has a "gotcha" clause concerning this specific case. Mozilla gotcha case

Answer

The parseInt has two parameters

parseInt(string, radix);

And map's callback accepts three parameters:

map(currentValue, index, array)

Therefore the index of the currentValue was passed as a radix to the parseInt function. Use parseInt with radix explicitly:

var s = "22123222222213123212322123213222";
var a = s.split("");
var b = a.map(e => parseInt(e, 10));

Or use Number instead of parseInt:

var s = "22123222222213123212322123213222";
var a = s.split("");
var b = a.map(Number);