Javascript 检查字符是否为数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8935632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if character is number?
提问by lisovaccaro
I need to check whether justPrices[i].substr(commapos+2,1)
.
我需要检查是否justPrices[i].substr(commapos+2,1)
.
The string is something like: "blabla,120"
字符串类似于:“blabla,120”
In this case it would check whether '0' is a number. How can this be done?
在这种情况下,它会检查“0”是否是一个数字。如何才能做到这一点?
回答by GregL
You could use comparison operators to see if it is in the range of digit characters:
您可以使用比较运算符来查看它是否在数字字符范围内:
var c = justPrices[i].substr(commapos+2,1);
if (c >= '0' && c <= '9') {
// it is a number
} else {
// it isn't
}
回答by Yaron U.
you can either use parseInt
and than check with isNaN
您可以使用parseInt
并检查isNaN
or if you want to work directly on your string you can use regexp like this:
或者如果你想直接处理你的字符串,你可以像这样使用正则表达式:
function is_numeric(str){
return /^\d+$/.test(str);
}
回答by Hymanocnr
EDIT: Blender's updated answer is the right answer here if you're just checking a single character (namely !isNaN(parseInt(c, 10))
). My answer below is a good solution if you want to test whole strings.
编辑:如果您只是检查单个字符(即!isNaN(parseInt(c, 10))
),Blender 的更新答案是正确的答案。如果您想测试整个字符串,我下面的回答是一个很好的解决方案。
Here is jQuery's isNumeric
implementation (in pure JavaScript), which works against full strings:
这是 jQuery 的isNumeric
实现(在纯 JavaScript 中),它适用于完整字符串:
function isNumeric(s) {
return !isNaN(s - parseFloat(s));
}
The comment for this function reads:
该函数的注释如下:
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
// parseFloat NaNs 数字转换误报 (null|true|false|"")
// ...但会误解前导数字字符串,尤其是十六进制文字 ("0x...")
// 减法将无穷大强制为 NaN
I think we can trust that these chaps have spent quite a bit of time on this!
我想我们可以相信这些家伙在这上面花了很多时间!
回答by Marian
I wonder why nobody has posted a solution like:
我想知道为什么没有人发布类似的解决方案:
var charCodeZero = "0".charCodeAt(0);
var charCodeNine = "9".charCodeAt(0);
function isDigitCode(n) {
return(n >= charCodeZero && n <= charCodeNine);
}
with an invocation like:
调用如下:
if (isDigitCode(justPrices[i].charCodeAt(commapos+2))) {
... // digit
} else {
... // not a digit
}
回答by user2486570
You can use this:
你可以使用这个:
function isDigit(n) {
return Boolean([true, true, true, true, true, true, true, true, true, true][n]);
}
Here, I compared it to the accepted method: http://jsperf.com/isdigittest/5. I didn't expect much, so I was pretty suprised, when I found out that accepted method was much slower.
在这里,我将其与公认的方法进行了比较:http: //jsperf.com/isdigittest/5。我没想到太多,所以当我发现接受的方法要慢得多时,我感到非常惊讶。
Interesting thing is, that while accepted method is faster correct input (eg. '5') and slower for incorrect (eg. 'a'), my method is exact opposite (fast for incorrect and slower for correct).
有趣的是,虽然接受的方法是更快的正确输入(例如“5”)和更慢的错误(例如“a”),但我的方法恰恰相反(快速输入错误,更慢输入正确)。
Still, in worst case, my method is 2 times faster than accepted solution for correct input and over 5 times faster for incorrect input.
尽管如此,在最坏的情况下,我的方法比正确输入的公认解决方案快 2 倍,错误输入快 5 倍以上。
回答by vsync
I think it's very fun to come up with ways to solve this. Below are some.
(All functions below assumeargument is a single character. Change to n[0]
to enforce it)
我认为想出解决这个问题的方法很有趣。下面是一些。
(以下所有函数都假定参数是单个字符。更改为n[0]
以强制执行)
Method 1:
方法一:
function isCharDigit(n){
return !!n.trim() && n > -1;
}
Method 2:
方法二:
function isCharDigit(n){
return !!n.trim() && n*0==0;
}
Method 3:
方法三:
function isCharDigit(n){
return !!n.trim() && !!Number(n+.1); // "+.1' to make it work with "." and "0" Chars
}
Method 4:
方法四:
var isCharDigit = (function(){
var a = [1,1,1,1,1,1,1,1,1,1];
return function(n){
return !!a[n] // check if `a` Array has anything in index 'n'. Cast result to boolean
}
})();
Method 5:
方法五:
function isCharDigit(n){
return !!n.trim() && !isNaN(+n);
}
Test string:
测试字符串:
var str = ' 90ABcd#?:.+', char;
for( char of str )
console.log( char, isCharDigit(char) );
回答by Jo?o Pimentel Ferreira
Simple function
简单的功能
function isCharNumber(c){
return c >= '0' && c <= '9';
}
回答by RobG
If you are testing single characters, then:
如果您正在测试单个字符,则:
var isDigit = (function() {
var re = /^\d$/;
return function(c) {
return re.test(c);
}
}());
will return true or false depending on whether c is a digit or not.
将根据 c 是否为数字返回 true 或 false。
回答by zenslug
I suggest a simple regex.
我建议一个简单的正则表达式。
If you're looking for just the last character in the string:
如果您只查找字符串中的最后一个字符:
/^.*?[0-9]$/.test("blabla,120"); // true
/^.*?[0-9]$/.test("blabla,120a"); // false
/^.*?[0-9]$/.test("120"); // true
/^.*?[0-9]$/.test(120); // true
/^.*?[0-9]$/.test(undefined); // false
/^.*?[0-9]$/.test(-1); // true
/^.*?[0-9]$/.test("-1"); // true
/^.*?[0-9]$/.test(false); // false
/^.*?[0-9]$/.test(true); // false
And the regex is even simpler if you are just checking a single char as an input:
如果您只是检查单个字符作为输入,则正则表达式甚至更简单:
var char = "0";
/^[0-9]$/.test(char); // true
回答by mmm
var Is = {
character: {
number: (function() {
// Only computed once
var zero = "0".charCodeAt(0), nine = "9".charCodeAt(0);
return function(c) {
return (c = c.charCodeAt(0)) >= zero && c <= nine;
}
})()
}
};