Array.map with parseInt returns unexpected result

6

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

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

He returned this to me:

  

[10, NaN, 2]

When this would be expected:

  

[10, 10, 10]

But if I do this:

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

It perfectly returns this:

  

[10, 10, 10]

I do not understand why this occurs, but I believe that parseInt may work the map array as a reference, ie in addition to return it modifies the reference directly to each loop in addition to return but I'm not sure.

What can it be?

    
asked by anonymous 12.04.2016 / 23:08

1 answer

11

When you use .map(parseInt); what is happening is:

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

That is, map() passes more than one argument to the callback. The .map() method passes 3 * arguments to the 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 therefore allows you to convert strings to numbers based on octal, decimal, hexadecimal, etc ... depending on the second argument that is assigned to it. This second parameter can be an integer between 2 and 36. In the absence of the 2nd argument the parseInt decides alone **, and this can lead to errors that are difficult to find.

  

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

     

** - In most browser implementations, the absence of the second argument causes the method to take base ten.

    
12.04.2016 / 23:12