2

I have the following JS Problem. If i try to convert an array of strings using the parseInt function as a mapped function with the Array.map method, i experienced this strange result. What is wrong here?

console.log(['1','1'].map(parseInt))

Returns a strange Array containing the following:

[1, NaN]

Is parseInt not a regular function?

parceval
  • 370
  • 4
  • 9

2 Answers2

3

parseInt takes multiple parameters. Array.map is run with multiple parameters.

to avoid side effects, you can run it like this:

console.log(['1','1'].map(function(item){
    return parseInt(item);
}))
Madd0g
  • 3,841
  • 5
  • 37
  • 59
1

Right, parseInt is not a regular function. It takes 2 arguments. The first is the number to parse, the second is the radix. Array.map passes 3 - the value, index, and full array.

Each call goes like this:

 parseInt('1', 0) // 1
 parseInt('1', 1) // NaN

To fix this, you need to manually call the function.

console.log(['1','1'].map(function(num){
    return parseInt(num);
}));
Scimonster
  • 32,893
  • 9
  • 77
  • 89