How to check if a JavaScript number is a real, valid number?

后端 未结 6 1517
礼貌的吻别
礼貌的吻别 2020-12-16 15:30

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          


        
6条回答
  •  爱一瞬间的悲伤
    2020-12-16 15:56

    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.

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

提交回复
热议问题