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?
the best way i found which also thinks of positive and negative numbers is from : O'Reilly Javascript and DHTML Cookbook :
}
Since ES2015 the correct way to check if a variable holds a valid number is:
Examples:
Here's an approach based on the idea of coercing the input to a number or string by adding zero or the null string, and then do a typed equality comparison.
For some unfathomable reason,
x===x+0
seems to perform better thanx===+x
.Are there any cases where this fails?
In the same vein:
This appears to be mildly faster than either
x===true || x===false
ortypeof x==="boolean"
(and much faster thanx===Boolean(x)
).Then there's also
All these depend on the existence of an "identity" operation particular to each type which can be applied to any value and reliably produce a value of the type in question. I cannot think of such an operation for dates.
For NaN, there is
This is basically underscore's version, and as it stands is about four times faster than
isNaN()
, but the comments in the underscore source mention that "NaN is the only number that does not equal itself" and adds a check for _.isNumber. Why? What other objects would not equal themselves? Also, underscore usesx !== +x
--but what difference could the+
here make?Then for the paranoid:
Simply use
or
if you want to handle strings defined as objects or literals and saves you don't want to use a helper function.