(Built-in) way in JavaScript to check if a string is a valid number

前端 未结 30 3411
-上瘾入骨i
-上瘾入骨i 2020-11-22 01:54

I\'m hoping there\'s something in the same conceptual space as the old VB6 IsNumeric() function?

30条回答
  •  遥遥无期
    2020-11-22 02:18

    This appears to catch the seemingly infinite number of edge cases:

    function isNumber(x, noStr) {
        /*
    
            - Returns true if x is either a finite number type or a string containing only a number
            - If empty string supplied, fall back to explicit false
            - Pass true for noStr to return false when typeof x is "string", off by default
    
            isNumber(); // false
            isNumber([]); // false
            isNumber([1]); // false
            isNumber([1,2]); // false
            isNumber(''); // false
            isNumber(null); // false
            isNumber({}); // false
            isNumber(true); // false
            isNumber('true'); // false
            isNumber('false'); // false
            isNumber('123asdf'); // false
            isNumber('123.asdf'); // false
            isNumber(undefined); // false
            isNumber(Number.POSITIVE_INFINITY); // false
            isNumber(Number.NEGATIVE_INFINITY); // false
            isNumber('Infinity'); // false
            isNumber('-Infinity'); // false
            isNumber(Number.NaN); // false
            isNumber(new Date('December 17, 1995 03:24:00')); // false
            isNumber(0); // true
            isNumber('0'); // true
            isNumber(123); // true
            isNumber(123.456); // true
            isNumber(-123.456); // true
            isNumber(-.123456); // true
            isNumber('123'); // true
            isNumber('123.456'); // true
            isNumber('.123'); // true
            isNumber(.123); // true
            isNumber(Number.MAX_SAFE_INTEGER); // true
            isNumber(Number.MAX_VALUE); // true
            isNumber(Number.MIN_VALUE); // true
            isNumber(new Number(123)); // true
        */
    
        return (
            (typeof x === 'number' || x instanceof Number || (!noStr && x && typeof x === 'string' && !isNaN(x))) &&
            isFinite(x)
        ) || false;
    };
    

提交回复
热议问题