I came across this while solving a problem... It was a fix something like that...
ar =[1.5,2,11.4,22,3,5,2]
Try: arr.map(parseInt)
==[1, NaN, 3, 8, 3, NaN, 2]
I get curious...
Analyzing the result a bit (only the first digits) I verified that the first number effectively converts it to number
my expected integer... but the second result always returns NaN so insert the same number ( [1,1]==[1,NaN]
) .. and the 3rd a 3?? Then I keep trying things.
[1,2,4]
== [1, NaN, NaN]
but.. [1,2,11]
== [1, NaN, 3]
??? I turned 3 into 11?? It has something to do with the fact that I already use 1...
More things if the array contains two string
consecutive ones at the beginning it doesn't return anything eg: ['1.5','2',22]
==
but... ['1.5',2,22,3,5,2]
== [ 1, NaN, NaN, NaN, NaN, 2 ]
????? If all the results returned in the examples are analyzed, strange things continue to be found, such as changes of NaN
alternate numbers depending on the previous numbers of the array... I found it interesting to share this, I am investigating because it happens... if someone already knows it and can remove the doubts I would appreciate it..
The parameters passed by the .map are
(currentValue, index, array)
And the parameters that .parseInt receives are
(string, base)
Therefore, knowing the parameters of each one, the problem can be inferred, El
.map(parseInt)
is equal to.map(parseInt(currentValue, index, array))
And since
parseInt
it only expects 2 parameters, the 3 ignores it, so itparseInt(string, base, array)
would be equal toparseInt(string, base)
When you do:
The following is actually executed:
Your code should be:
A longer version of this question/answer:
Why ['1', '7', '11'].map(parseInt) returns [1, NaN, 3] in Javascript
Regarding the comment:
As you say, the most intuitive thing is that
parseInt('11.4', 2, [1, 2, 11, 22, 3, 5, 2]);
or what is the sameparseInt('11.4', 2)
, the result isNaN
since it11.4
is not a feasible number for base 2.It seems that in these cases it parses as much as it can until it comes across a character other than
0
or1
:As @x3k_js says, what happens is that you are passing the index of the element as the base of
parseInt
the test would be:The base parameter of
parseInt
is the base in which the number passed by parameter is expressed, not the result, and this must be between 2 and 36. Outside of these values, it is assumed to be base 10 if the string does not begin with "0x" neither with "0" or isundefined
, 1 should perhaps return base 10 but apparently it is executed astrue
, so it does not recognize any symbol, which givesNaN
.So what happens is that if we put base 3, it means that the number we pass as a parameter has to be formed with the digits 0, 1, 2. Otherwise it is
NaN
. Examples:So the strange behavior you have is fundamentally because symbols are passed that are not within the specified base.
NaN
NaN
NaN
NaN