I'm hoping there's something in the same conceptual space as the old VB6 IsNumeric()
function?
相关问题
- 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?
You could make use of types, like with the flow library, to get static, compile time checking. Of course not terribly useful for user input.
If you're just trying to check if a string is a whole number (no decimal places), regex is a good way to go. Other methods such as
isNaN
are too complicated for something so simple.To only allow positive whole numbers use this:
I have tested and Michael's solution is best. Vote for his answer above (search this page for "If you really want to make sure that a string" to find it). In essence, his answer is this:
It works for every test case, which I documented here: https://jsfiddle.net/wggehvp9/5/
Many of the other solutions fail for these edge cases: ' ', null, "", true, and []. In theory, you could use them, with proper error handling, for example:
or
with special handling for /\s/, null, "", true, false, [] (and others?)
You can use the result of Number when passing an argument to its constructor.
If the argument (a string) cannot be converted into a number, it returns NaN, so you can determinate if the string provided was a valid number or not.
Notes: Note when passing empty string or
'\t\t'
and'\n\t'
as Number will return 0; Passing true will return 1 and false returns 0.Why is jQuery's implementation not good enough?
Michael suggested something like this (although I've stolen "user1691651 - John"'s altered version here):
The following is a solution with most likely bad performance, but solid results. It is a contraption made from the jQuery 1.12.4 implementation and Michael's answer, with an extra check for leading/trailing spaces (because Michael's version returns true for numerics with leading/trailing spaces):
The latter version has two new variables, though. One could get around one of those, by doing:
I haven't tested any of these very much, by other means than manually testing the few use-cases I'll be hitting with my current predicament, which is all very standard stuff. This is a "standing-on-the-shoulders-of-giants" situation.
PFB the working solution: