Why does parseInt (['1', '2', '3']) return 1?

parseInt([1,2,3])
1
parseInt([[1,2,3]])
1
parseInt([[['101',2,3]]], 2)
5

Tested with Chrome12, Firefox3.6, IE6, IE8.

+3
source share
4 answers

Because it [1,2,3].toString()will return 1,2,3, so you get 1the first two lines. parseInt()will stop looking for a numeric value after it reaches the value NaN, which in this case is a comma ,. Where he stops analyzing and returns everything that he has found so far.

+5
source

parseIntwill do the first thing that can reasonably go into your mess of arrays - in this case '101'.

And then,

>>> parseInt(101, 2)
5

Since 101 2= 5 10

+5
source

, parseInt , ,

parseInt([1,2,3]) parseInt([1,2,3].toString()), parseInt("1,2,3")

+4

It takes the first value in the array, and then uses the radix value to convert the value to int.

parseInt([50,2,3])
Will return to you 50

parseInt([[['101',2,3]]], 2)

Returns 5 because the first 101base element 2is int 5 base 10.

0
source

All Articles