Does anyone know how can I check whether a variable is a number or a string in JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
For detecting numbers, the following passage from JavaScript: The Good Parts by Douglas Crockford is relevant:
or just use the invert of isNaN
if(!isNaN(data)) do something with the number else it is a string
and yes - using jQuery - $.isNumeric() is more fun for the buck.
This solution resolves many of the issues raised here!
This is by far the most reliable method I have used by far. I did not invent this, and cannot recall where I originally found it. But it works where other techniques fail:
Example of correctness
Created a jsperf on the checking if a variable is a number. Quite interesting! typeof actually has a performance use. Using
typeof
for anything other than numbers, generally goes a 1/3rd the speed as avariable.constructor
since the majority of data types in javascript are Objects; numbers are not!http://jsperf.com/jemiloii-fastest-method-to-check-if-type-is-a-number
typeof variable === 'number'
| fastest | if you want a number, such as 5, and not '5'typeof parseFloat(variable) === 'number'
| fastest | if you want a number, such as 5, and '5'isNaN()
is slower, but not that much slower. I had high hopes forparseInt
andparseFloat
, however they were horribly slower.I think converting the var to a string decreases the performance, at least this test performed in the latest browsers shows so.
So if you care about performance, I would, I'd use this:
for checking if the variable is a string (even if you use
var str = new String("foo")
,str instanceof String
would return true).As for checking if it's a number I would go for the native:
isNaN
; function.since a string as '1234' with typeof will show 'string', and the inverse cannot ever happen (typeof 123 will always be number), the best is to use a simple regex
/^\-?\d+$/.test(var)
. Or a more advanced to match floats, integers and negative numbers,/^[\-\+]?[\d]+\.?(\d+)?$/
The important side of.test
is that it WON'T throw an exception if the var isn't an string, the value can be anything.If you are looking for the real type, then typeof alone will do.