如何检查 JavaScript 数字是否是真实有效的数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8525899/
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
How to check if a JavaScript number is a real, valid number?
提问by Rob W
MY code is:
我的代码是:
function isNumber(n){
return typeof n == 'number' && !isNaN(n);
}
window.onload=function(){
var a=0,b=1,c=2.2,d=-3,e=-4.4,f=10/3;
var shouldBeTrue=[a,b,c,d,e,f];
var aa="0",bb="1",cc="2.2",dd="-3",ee="-4.4",ff="10/3";
var shouldBeFalse=[aa,bb,cc,dd,ee,ff];
var aaa,bbb=true,ccc=false,ddd=document.getElementsByTagName('html');
var alsoTheseBeFalse=[aaa,bbb,ccc,ddd,""," ",,null,NaN];
for(var i=0;i<shouldBeTrue.length;i++)
if(isNumber(shouldBeTrue[i]) != true) alert("x");
for(i=0;i<shouldBeFalse.length;i++)
if(isNumber(shouldBeFalse[i]) != false) alert("x");
for(i=0;i<alsoTheseBeFalse.length;i++)
if(isNumber(alsoTheseBeFalse[i]) != false) alert("x");
}
What else should I check against to ensure my function is 101% perfect in all ways? (also, if you know a better function please tell me)
我还应该检查什么以确保我的功能在所有方面都 101% 完美?(另外,如果您知道更好的功能,请告诉我)
回答by Rob W
If you want to check whether a number is a real number, you should also check whether it's finite:
如果你想检查一个数是否是实数,你还应该检查它是否有穷:
function isNumber(n){
return typeof n == 'number' && !isNaN(n) && isFinite(n);
}
Another method (explanation below):
另一种方法(解释如下):
function isNumber(n){
return typeof n == 'number' && !isNaN(n - n);
}
Update: Two expressions to validate a real number
更新:验证实数的两个表达式
Since JavaScript numbers are representing real numbers, the substraction operand on the same number should produce the zero value (additive identity). Numbers out of range should (and will) be invalid, NaN
.
由于 JavaScript 数字代表实数,因此相同数字的减法操作数应产生零值(加法标识)。超出范围的数字应该(并且将)无效,NaN
.
1 - 1 = 0 // OK
Infinity - Infinity = NaN // Expected
NaN - NaN = NaN // Expected
NaN - Infinity = NaN
回答by Oriol
JS numbers can be among the following values:
JS 编号可以是以下值:
- Finite numbers
+Infinity
and-Infinity
NaN
- 有限数
+Infinity
和-Infinity
NaN
Then there also non-number values which are coercible to numbers, e.g. number objects. You might want to consider them numerical.
然后还有可强制转换为数字的非数字值,例如数字对象。您可能希望将它们视为数字。
If you only want to test finite numbers, simply use Number.isFinite
:
如果您只想测试有限数,只需使用Number.isFinite
:
Number.isFinite(value)
var isNumber = Number.isFinite;
assert('isNumber(1)', true);
assert('isNumber(1.1)', true);
assert('isNumber(+0)', true);
assert('isNumber(-0)', true);
assert('isNumber(-1.1)', true);
assert('isNumber(Math.PI)', true);
assert('isNumber(1e300)', true);
assert('isNumber(+Infinity)', false);
assert('isNumber(-Infinity)', false);
assert('isNumber(NaN)', false);
assert('isNumber(null)', false);
assert('isNumber(undefined)', false);
assert('isNumber(true)', false);
assert('isNumber(false)', false);
assert('isNumber("123")', false);
assert('isNumber("foo")', false);
assert('isNumber(new Number(1))', false);
assert('isNumber([])', false);
assert('isNumber({})', false);
assert('isNumber(function(){})', false);
function assert(code, expected) {
var result = eval(code);
console.log('Test ' + (result===expected ? 'pass' : 'FAIL') + ': ', code, ' -> ', result);
}
If you want to include infinities, check the type and exclude NaN
:
如果要包含无穷大,请检查类型并排除NaN
:
typeof value === "number" && !Number.isNaN(value)
function isNumber(value) {
return typeof value === "number" && !Number.isNaN(value);
}
assert('isNumber(1)', true);
assert('isNumber(1.1)', true);
assert('isNumber(+0)', true);
assert('isNumber(-0)', true);
assert('isNumber(-1.1)', true);
assert('isNumber(Math.PI)', true);
assert('isNumber(1e300)', true);
assert('isNumber(+Infinity)', true);
assert('isNumber(-Infinity)', true);
assert('isNumber(NaN)', false);
assert('isNumber(null)', false);
assert('isNumber(undefined)', false);
assert('isNumber(true)', false);
assert('isNumber(false)', false);
assert('isNumber("123")', false);
assert('isNumber("foo")', false);
assert('isNumber(new Number(1))', false);
assert('isNumber([])', false);
assert('isNumber({})', false);
assert('isNumber(function(){})', false);
function assert(code, expected) {
var result = eval(code);
console.log('Test ' + (result===expected ? 'pass' : 'FAIL') + ': ', code, ' -> ', result);
}
If you want to consider number objects as numbers, you can unwrap them using
如果您想将数字对象视为数字,您可以使用
value = Number.valueOf.call(value); // throws if value was not a number object
function isNumber(value) {
try { value = Number.prototype.valueOf.call(value); } catch(err) { }
return Number.isFinite(value);
}
assert('isNumber(1)', true);
assert('isNumber(1.1)', true);
assert('isNumber(+0)', true);
assert('isNumber(-0)', true);
assert('isNumber(-1.1)', true);
assert('isNumber(Math.PI)', true);
assert('isNumber(1e300)', true);
assert('isNumber(+Infinity)', false);
assert('isNumber(-Infinity)', false);
assert('isNumber(NaN)', false);
assert('isNumber(null)', false);
assert('isNumber(undefined)', false);
assert('isNumber(true)', false);
assert('isNumber(false)', false);
assert('isNumber("123")', false);
assert('isNumber("foo")', false);
assert('isNumber(new Number(1))', true);
assert('isNumber([])', false);
assert('isNumber({})', false);
assert('isNumber(function(){})', false);
function assert(code, expected) {
var result = eval(code);
console.log('Test ' + (result===expected ? 'pass' : 'FAIL') + ': ', code, ' -> ', result);
}
If you want to include arbitrary values coercible to numbers, you can use the unary +
to coerce.
如果要包含可+
强制转换为数字的任意值,可以使用一元进行强制。
value = +value; // throws if value was not number-coercible
There is also the isNaN
function (not to be confused with Number.isNaN
), which will first coerce and then compare with NaN
. But be aware whitespace strings and null
are coerced to +0
, not NaN
. So you might be interested in Validate decimal numbers in JavaScript - IsNumeric()
还有一个isNaN
函数(不要与 混淆Number.isNaN
),它会先强制,然后与 进行比较NaN
。但请注意空格字符串和null
被强制为+0
,而不是NaN
。所以你可能对在 JavaScript中验证十进制数感兴趣- IsNumeric()
回答by Ameer Khalaf
I use combination of parse and check for numbers.. as outlined below
我使用解析和检查数字的组合.. 如下所述
function isNumber(inputValue){
return ((parseFloat(inputValue) ==0 || parseFloat(inputValue)) && !isNaN(inputValue));
};
function isNumber(inputValue){
return ((parseFloat(inputValue) ==0 || parseFloat(inputValue)) && !isNaN(inputValue));
};
hope this helps
希望这可以帮助
回答by Sunil Jhamnani
For react or other framework users, possible solution could be:
对于 react 或其他框架用户,可能的解决方案可能是:
const { onChange, value } = this.props;
return (
<input
type="text" // Note: I have kept this as text
value={typeof value !== 'number' || isNaN(value) ? '' : value}
className={classnames('input')}
onChange={(event) =>
onChange &&
onChange(parseFloat(event.target.value))
}
/>)
This works on safari as well.
这也适用于 safari。
Thanks.
谢谢。
回答by Jukka K. Korpela
It depends on what you wish to regard as a number. Your code classifies Infinity and -Infinity as numbers. If you don't want that, replace !isNaN(n) by isFinite(n).
这取决于您希望将什么视为数字。您的代码将 Infinity 和 -Infinity 分类为数字。如果您不希望那样,请将 !isNaN(n) 替换为 isFinite(n)。
And your code classifies '42' (a string literal) as not being a number, due to the type check; but I supposed that's intentional.
由于类型检查,您的代码将“42”(字符串文字)分类为不是数字;但我想那是故意的。
回答by RightSaidFred
If you consider a number in its object wrapper to be a number, then it will fail with:
如果您将其对象包装器中的数字视为数字,则它将失败并显示:
isNumber( new Number(123) )
Since a downvoter is having some comprehension troubles that couldn't be alleviated by a simple test, new Number(123)
will return 'object'
from the typeof
test, and as such will not pass.
由于downvoter 有一些无法通过简单测试缓解的理解问题,因此new Number(123)
会'object'
从typeof
测试中返回,因此不会通过。