2

When I execute the following statements:

var string = "1 1 1 1 1 1 0 1 1"
console.log(string)
var strings = string.split(" ")
console.log(strings)
var numbers1 = strings.map(parseInt)
console.log(numbers1)
var numbers2 = strings.map(function(i){ return parseInt(i, 10) })
console.log(numbers2)

I get the following output in the console:

1 1 1 1 1 1 0 1 1
["1", "1", "1", "1", "1", "1", "0", "1", "1"]
[1, NaN, 1, 1, 1, 1, 0, 1, 1]
[1, 1, 1, 1, 1, 1, 0, 1, 1]

I wonder why the second element in numbers1 is NaN. Why does it work on all the other elements except this one?

Tushar
  • 85,780
  • 21
  • 159
  • 179
Peppe L-G
  • 7,351
  • 2
  • 25
  • 50

2 Answers2

7

It is because map passes additional arguments.

Array.prototype.map = function(currentValue, index, array)

So when it is at index 1, it passes 1 as the radix.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
3

Array.prototype.map has three arguments that pass to the callback we set as argument:

* value
* index
* arr

When we check the specifications of parseInt we can see that parseInt could receive two arguments.

* string
* radix

The former is the string to be parsed and the latter is the ratio to convert the value.

When we run Snippet 1 code, the following is actually

> parseInt("1", 0) // 1

> parseInt("1", 1) // NaN

> parseInt("1", 2) // 1

> parseInt("1", 3) // 1


You can use Arrow function with parseInt

array.map(e => parseInt(e, 10));

Use Number instead of parseInt.

arr.map(Number);

Or you can also use the anonymous function.

arr.map(function(num) {
    return parseInt(num, 10);
});
Community
  • 1
  • 1
Tushar
  • 85,780
  • 21
  • 159
  • 179