-2

I would like to parse integers as they are written to a new array. Here are two versions I have:

let aa = '123';
let bb = Array.from(aa, (val) => parseInt(val));
// [1,2,3] OK
let cc = Array.from(aa, parseInt);
// [1, NaN, NaN]
console.log(aa, bb, cc);

Why does the first method work, but the second method does not (doesn't parseInt take one required argument, so would be the same as the first method?)

David542
  • 104,438
  • 178
  • 489
  • 842
  • 3
    _"doesn't parseInt take one argument"_... I guess you haven't [checked the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#parameters) – Phil Oct 14 '21 at 22:18
  • @phil -- sure, the radix is optional though, so how is parseInt called in the above invocation? – David542 Oct 14 '21 at 22:19
  • 2
    It is the same reason as outlined in this answer: https://stackoverflow.com/q/262427/5648954 – Nick Parsons Oct 14 '21 at 22:19
  • 3
    @David542 `Array.from(data, (el, index) =>` - you are passing the index as the second argument, which is then being treated as the radix – dave Oct 14 '21 at 22:21
  • @dave thanks again. I think this is the correct answer, not quite touched on in the Duplicates from briefly glancing over some of the answers. – David542 Oct 14 '21 at 22:22

1 Answers1

0

parseInt() takes two arguments, the second argument defines the radix (base) for the parsed number.

P. S. You could use the Number constructor as the second argument:

let cc = Array.from(aa, Number);
Maksym Shcherban
  • 742
  • 4
  • 13
  • 3
    to expand, `Array.from` will pass `(element, index)`, so your radix will be the index of each element, causing undesirable results – dave Oct 14 '21 at 22:19
  • @dave ah, got it. Yes I think that was actually what I didn't understand. – David542 Oct 14 '21 at 22:20