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?
parseInt()at all? The only two things I would use it for are (a) non-base 10 input, and (b) parsing an input string in a known format like a CSS"10px"where I just want the10part. I believeNumber([21,22])returnsNaN, as does the unary plus operator+[21,23].if isNaN(parseInt(argument1)).... Quick and easy. What's the harm? I'm not being flip. I'm genuinely curious.argument1is the string"123abc", that's not a valid number, butparseInt("123abc")returns123. If that's the result you actually want, then sure, useparseInt(), but in my experience it's pretty rare for that to make sense (I gave an example already where it does make sense). If you want to test that a function argument is already a number (and not an object or array) you can use thetypeofoperator.