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?

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.