Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with parseInt? [duplicate]

Tags:

javascript

Possible Duplicate:
javascript - Array.map and parseInt

I stumbled across the following code snippet:

> ['10','10','10','10','10'].map(parseInt);
[10, NaN, 2, 3, 4]

What's happening here?

like image 743
shredding Avatar asked Jan 26 '13 08:01

shredding


2 Answers

Start by consulting the documentation for Array.prototype.map. The key is this line:

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

(emphasis mine)

Then check the documentation for parseInt:

The parseInt function converts its first argument to a string, parses it, and returns an integer or NaN. If not NaN, the returned value will be the decimal integer representation of the first argument taken as a number in the specified radix (base). For example, a radix of 10 indicates to convert from a decimal number, 8 octal, 16 hexadecimal, and so on. For radices above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.

and:

If radix is undefined or 0, JavaScript assumes the following:

  • If the input string begins with "0x" or "0X", radix is 16 (hexadecimal).

  • If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.

  • If the input string begins with any other value, the radix is 10 (decimal).

So the first call is:

parseInt('10',0, ['10','10',...]) // => 10 (because radix=0)

the second is:

parseInt('10',1, ['10','10',...]) // => NaN because radix is 1

the third:

parseInt('10',2, ['10','10',...]) // => 2 because 10 in binary is the number "2"

and so on.

like image 137
geocar Avatar answered Nov 16 '22 11:11

geocar


From MDN docu:

parseInt is often used with one argument, but takes two. The second being the radix To the callback function, Array.prototype.map passes 3 arguments: the element, the index, the array The third argument is ignored by parseInt, but not the second one, hence the possible confusion.

So actually your parseInt is passed the folowing values:

// 1st run:
parseInt( '10', 0 );
// 2nd run:
parseInt( '10', 1 );
// etc.

So you're using a different radix every time, leading to the results seen.

like image 5
Sirko Avatar answered Nov 16 '22 10:11

Sirko