Javascript map weird behavior

I fixed some problems with code objects and tried to convert a string to a list of numbers like this:

"102904".split("").map(parseInt);

The expected result will be something like this:

[1, 0, 2, 9, 0, 4]

But instead, it returns:

[1, NaN, NaN, NaN, 0, 4]

Consider that the card should apply to each item in the list that contains 1-digit strings. One would think that it does not understand correctly, because the database is not used, but:

"102904".split("").map(function(x){ return parseInt(x);});
[ 1, 0, 2, 9, 0, 4]

Use parseInt(x, 10)does not change the result. But sending directly parseInt to the card creates NaN...

I tried Chrome and Firefox and get the same results.

+4
source share
3 answers

, Array.prototype.map, :

parseInt, radix – . ,

string | base | result
----------------------
1      | 0    | 1
0      | 1    | NaN
2      | 2    | NaN
9      | 3    | NaN
0      | 4    | 0
4      | 5    | 4

, base 0 ( ), 1, NaN. , parseInt 0 :

radix undefined 0 ( ), JavaScript : (MDN docs)

+1

parseInt - radix.

, - map : .

: 0, 2, 9

?

  • 0 - radix, 1. 1 , NaN
  • 2 - , 2. 2- 2 (0 1 )
  • 9 - radix, 3. 9 (0, 1 2 )
+7
"102904".split("").map(function(x, y){ console.log(x, y) });

returns

1 0
0 1
2 2
9 3
0 4
4 5

This means that in the first example it parseIntis called as follows:

parseInt("1", 0);
parseInt("0", 1);
parseInt("2", 2);
parseInt("9", 3);
// ecc...

You pass the iteration index as the second parameter to parseInt()(which is the radius of the number to be analyzed).


The best solution is to use the second approach with the code already published.

+1
source

All Articles