如何检查JavaScript编号是否真实有效? [英] How to check if a JavaScript number is a real, valid number?

查看:98
本文介绍了如何检查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数字代表实数,因此相同数字上的减法操作数应产生零值(加性身份)。超出范围的数字应该(并且将)无效, 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

这篇关于如何检查JavaScript编号是否真实有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆