javascript,判断 val 是否为单个数字的最佳方法
判断 javascript 中的值是否为单个数字的最佳方法是什么。我一直在做类似
var valAsString = '' + val;
if (valAsString.match(/\d/) {}
澄清的事情:我的意思是 0,1,2,3,4,5,6,7,8,9 之一
另外,我应该做些什么吗?我很惊讶人们为此想出了这么多不同的方法。
whats the best way to tell if a value in javascript is a single digit. Ive been doing something like
var valAsString = '' + val;
if (valAsString.match(/\d/) {}
clarification: I mean one of 0,1,2,3,4,5,6,7,8,9
Also, should what I have work? Im surprised how many different ways people are coming up with for this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
/\d/
正则表达式将匹配字符串中任意位置的数字,例如"foo1"
将匹配"1"
。对于正则表达式方法,需要这样的方法,以确保字符串包含单个数字:
请注意,我使用的是
test
方法,当您只想检查字符串是否匹配时建议使用该方法该模式,以及test
方法内部将转换为字符串参数。另一种简短的非正则表达式方法:
The
/\d/
regexp will match a digit anywhere on a string, for example in"foo1"
will match"1"
.For a regexp approach need something like this, to ensure that the string will contain a single digit:
Note that I'm using the
test
method, which is recommended when you only want to check if a string matches the pattern, also, thetest
method internally will convert to sting the argument.Another short non-regexp approach:
嗯,检查一下它的字符串长度是否等于 1?
但这不接受负数或带有小数部分的数字。
Ummm, check if it's string length is equal to one?
This won't accept negative numbers or numbers with decimal components though.
如果您不想包含负数,这将有效,您的解决方案也将有效。
您可以只检查字符串是否在 -10 到 10 之间(假设您想包含负数)。这将是最快的,但不适用于非整数,因此最好避免它。
如果您确实想包含负数,我可能会检查该数字是否为整数,然后我会采用如下方法:
If you don't want to include negatives this will work, as will your solution.
You could just check if the string is between -10 and 10 (assuming you want to include negatives). This will be fastest, but will not work for non-integers, so its probably best avoided.
If you do want to include negatives I'd probably check to see if the number is an integer then I'd go with something like this:
假设
val
已经是数字...Assuming that
val
is already numeric...您可以对正则表达式进行以下修改:
valAsString.match(/^\d$/)
You can use the below modification of your regular expression:
valAsString.match(/^\d$/)
我认为
应该这样做,假设您只想接受
number
类型的值。更干净的解决方案
可以轻松地适应包括其他类型的值。
I think
should do it, assuming you only want to accept values of type
number
.A cleaner solution is
which can be easily adapted to include values of other types.
像这样的事情怎么样:
How about something like this: