Array.map with parseint returns unexpected result

Asked

Viewed 88 times

8

I was seeing a comment from jbueno in chat and decided to test in the browsers IE, Firefox and Chrome, while running on the consoles this command:

['10', '10', '10'].map(parseInt);

He returned this to me:

[10, Nan, 2 Nan]

When the expected would be this:

[10, 10, 10]

But if I do so:

['10', '10', '10'].map(function(a) { return parseInt(a); });

He returns it perfectly:

[10, 10, 10]

I don’t understand why this happens, but I believe that maybe the parseInt work the array of map as a reference, that is to say, beyond the return it modifies the reference directly to each loop beyond the return, but I’m not sure.

What can it be?

1 answer

13


When you use .map(parseInt); what’s going on is:

['10', '10', '10'].map(function(el, index, array) {
    var res = parseInt(el, index);
    return res;
});

That is, the map() passes more than one argument to callback. The method .map() passes 3* arguments to callback, and the second argument is being treated as Radix by parseInt(str, radix);.

Examples:

var A = ['10', '10', '10'].map(function(el, index) {
    return parseInt(el, index);
});

var B = ['10', '10', '10'].map(function(el, index) {
    return parseInt(el, 10); // <-- aqui damos o radix como fixo, base 10
});

console.log(A, '|', B); // dá [10, NaN, 2] "|" [10, 10, 10]

The parseInt allows therefore to convert strings into numbers based on octal, decimal, hexadecimal, etc... depending on the second argument assigned to it. This second parameter can be an integer between 2 and 36. In the absence of 2nd argument o parseInt decide on its own**, and this can lead to hard-to-find errors.

* - The method .map() passes 3 arguments. The array element to be iterated, the index or position that element has in the Array, and finally its own Array.

** - In most browser implementations the absence of the second argument makes the method take basis ten.

  • 4

    It is irrelevant in this case, but remember that the callback also takes the source array as the third argument.

  • @pathetically correct. I was editing and added this as well. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.