0

Here's a basic function in JavaScript which should convert an array of numeral strings into an array of integers.

function convert(arr) {
  return arr.map(parseInt,10);
}

The result of running

convert(["1","2","3","4","5"]);

should be to return

[1,2,3,4,5]

. However the function returns:

[1, NaN, NaN, NaN, NaN]

I know that if the parseInt() function encounters a character which is not a numeral, it returns NaN. I also know that the method will work if the Array.prototype.map() function is replaced with a conventional for () loop, so the culprit seems to be the .map() function. Does anyone know why .map() works normally on the first indice in the array but does not work on the others?

Thanks.

  • What do you think the second argument passed to `.map` does? – Felix Kling Jan 19 '17 at 01:58
  • It's not an exact duplicate, so I will clarify: The second parameter for [`map`](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/map) is not an additional argument to pass to the function but the `thisArgument`, so it will call something like `10.parseInt(2)` in your case. – Yogu Jan 19 '17 at 01:58
  • The problem is actually that `parseInt` takes two arguments and `Array.prototype.map` passes 3 arguments to its callback, the second of which is the index. 0 is falsy, so `parseInt` defaults to 10, while the next index (1) is truthy and `n` base `n-1` is always `NaN`. – erbridge Jan 19 '17 at 02:02
  • @Yogu—the first part of your comment is correct, however the value of *this* isn't set that way. It sets the *this* of the callback to the second argument, it doesn't call the callback as a method of the second argument (noting that built–in functions can behave in ways that native functions can't). – RobG Jan 19 '17 at 02:45
  • @RobG that's why I wrote *something like*, just for illustration purposes. Of course, your explanation is more accurate. – Yogu Jan 19 '17 at 07:10
  • I was thinking that might be the problem. Thanks. I had not used lambda notation with JavaScript until now. – Carlo Felicione Jan 19 '17 at 08:30

0 Answers0