2

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

GusOst
  • 4,105
  • 3
  • 19
  • 28

1 Answers1

2

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);
isvforall
  • 8,768
  • 6
  • 35
  • 50
  • `a.map` passes the array's value, index, and the array itself in that order to `parseInt` (or in the case of this answer, `Number`). Ergo why `radix` is important to note. – notacouch Apr 27 '16 at 22:57
  • 1
    `.map()` provides the index (0, 1, 2, ...) that's used as the `radix`. – Jonathan Lonowski Apr 27 '16 at 22:58