如何检查 JavaScript 数字是否是真实有效的数字?

2022-01-17 00:00:00 numbers int javascript

我的代码是:

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");
}

我还应该检查什么以确保我的功能在所有方面都 101% 完美?(另外,如果你知道更好的功能请告诉我)

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)

推荐答案

如果要检查一个数是否为实数,还应该检查它是否是有限的:

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);
}

更新:验证实数的两个表达式

由于 JavaScript 数字表示实数,相同数字的减法操作数应该产生零值 (additive身份).超出范围的数字应该(并且将会)无效,NaN.

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.

1        - 1        = 0    // OK
Infinity - Infinity = NaN  // Expected
NaN      - NaN      = NaN  // Expected
NaN      - Infinity = NaN

相关文章