Question:
I was seeing a comment from jbueno in the chat and decided to test it in IE, Firefox and Chrome browsers, when running this command on the consoles:
['10', '10', '10'].map(parseInt);
He returned this to me:
[10, NaN, 2]
When would you expect this to be:
[10, 10, 10]
But if I do like this:
['10', '10', '10'].map(function(a) { return parseInt(a); });
It perfectly returns this:
[10, 10, 10]
I don't understand why this happens, but I believe that maybe parseInt
works the map
array as a reference, that is, besides the return
it modifies the reference directly in each loop besides the return
, but I'm not sure.
What can it be?
Answer:
When you use .map(parseInt);
what's 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 byparseInt(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]
parseInt
therefore allows you to convert strings into numbers with octal, decimal, hexadecimal, etc… base depending on the second argument assigned to it. This second parameter can be an integer between 2 and 36. In the absence of a 2nd argument parseInt
decides on its own**, and this can lead to hard-to-find errors.
* – The
.map()
method passes 3 arguments. The element of the array to be iterated, the index or position that this element has in the Array, and finally the Array itself .** – In most browser implementations the absence of the second argument makes the method assume base ten.