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?
Very late to the party; however, the following has always worked well for me when I want to check whether some input is either a string or a number in one shot.
Try this,
jQuery uses this:
The best way I have found is to either check for a method on the string, i.e.:
or if you want to do something with the number check for a number property,
This is sort of like "duck typing", it's up to you which way makes the most sense. I don't have enough karma to comment, but typeof fails for boxed strings and numbers, i.e.:
will alert "object".
You're looking for
isNaN()
:See JavaScript isNaN() Function at MDN.
Can you just divide it by 1?
I assume the issue would be a string input like: "123ABG"
Just a way I did it recently.