Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does parseInt fail to test Arrays properly in Javascript?

Given:

var obj={0:21,1:22}

and

var arr=[21,22]

Why does parseInt(obj) return NaN, but parseInt(arr) returns 21?

I had a function where I was either going to pass an int, a hash type object or a plain array. I was expecting parseInt to return NaN for both object and array, thus simplifying argument checking. What gives?

like image 955
dgo Avatar asked Feb 06 '23 02:02

dgo


1 Answers

This is because parseInt tries to coerce the first argument to a string before parsing to an integer. String(obj) returns "[object Object]" and can't be parsed, but String([21,23]) returns "21,23", which parseInt parses until it reaches the unparseable char.

See the parseInt spec:

Let inputString be ? ToString(string).

(Coerce the input to a string).

If S contains a code unit that is not a radix-R digit, let Z be the substring of S consisting of all code units before the first such code unit; otherwise, let Z be S.

(Drop any part of the string starting with non-digit character, so "21,23" -> "21").

like image 90
nrabinowitz Avatar answered Feb 07 '23 17:02

nrabinowitz