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?
If you're dealing with literal notation, and not constructors, you can use typeof:.
If you're creating numbers and strings via a constructor, such as
var foo = new String("foo")
, you should keep in mind thattypeof
may returnobject
forfoo
.Perhaps a more foolproof method of checking the type would be to utilize the method found in underscore.js (annotated source can be found here),
This returns a boolean
true
for the following:@BitOfUniverse's answer is good, and I come up with a new way:
I know
0
can't be dividend, but here the function works perfectly.uh, how about just:
After further review many months later, this only guarantees
obj
is an object that has the method or property nametoLowerCase
defined. I am ashamed of my answer. Please see top-votedtypeof
one.Or adapt it to return an unknown type:
May 12, 2012 Update: Full example at Javascript: A Better typeof.
Jsut an FYI, if you're using jQuery you have
to handle this. More details on http://api.jquery.com/jQuery.isNumeric/