Why isNaN('') or isNaN(“”) is false (one quote or double quotes are considered a valid number)?

后端 未结 3 1556
傲寒
傲寒 2021-01-27 23:49

I need a built in function that checks if a variable contains a valid number in Javascript , following this link I\'ve tried to use is isNaN , however when I use on

3条回答
  •  走了就别回头了
    2021-01-28 00:10

    Any thing which cannot be converted to number should return true, But "" string can be parsed to number so it returns false

    console.log(+"")
    console.log(Number(""))
    console.log(isNaN(""))

    A polyfill for isNaN looks like this

    var isNaN = function(value) {
        var n = Number(value);
        return n !== n;
    };
    
    console.log(isNaN(""))

    Note:- Things get confusing when you try parseInt on these values. But the parseInt specs literally says it returns NaN the first non-whitespace character cannot be converted to a number. or radix is below 2 or above 36.

    console.log(parseInt(""))

提交回复
热议问题