How do you check that a number is NaN in JavaScript?

前端 未结 30 2627
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 06:19

I’ve only been trying it in Firefox’s JavaScript console, but neither of the following statements return true:

parseFloat(\'geoff\') == NaN;

parseFloat(\'ge         


        
相关标签:
30条回答
  • 2020-11-22 06:39

    NaN in JavaScript stands for "Not A Number", although its type is actually number.

    typeof(NaN) // "number"
    

    To check if a variable is of value NaN, we cannot simply use function isNaN(), because isNaN() has the following issue, see below:

    var myVar = "A";
    isNaN(myVar) // true, although "A" is not really of value NaN
    

    What really happens here is that myVar is implicitly coerced to a number:

    var myVar = "A";
    isNaN(Number(myVar)) // true. Number(myVar) is NaN here in fact
    

    It actually makes sense, because "A" is actually not a number. But what we really want to check is if myVar is exactly of value NaN.

    So isNaN() cannot help. Then what should we do instead?

    In the light that NaN is the only JavaScript value that is treated unequal to itself, so we can check for its equality to itself using !==

    var myVar; // undefined
    myVar !== myVar // false
    
    var myVar = "A";
    myVar !== myVar // false
    
    var myVar = NaN
    myVar !== myVar // true
    

    So to conclude, if it is true that a variable !== itself, then this variable is exactly of value NaN:

    function isOfValueNaN(v) {
        return v !== v;
    }
    
    var myVar = "A";
    isNaN(myVar); // true
    isOfValueNaN(myVar); // false
    
    0 讨论(0)
  • 2020-11-22 06:39

    The rule is:

    NaN != NaN
    

    The problem of isNaN() function is that it may return unexpected result in some cases:

    isNaN('Hello')      //true
    isNaN('2005/12/12') //true
    isNaN(undefined)    //true
    isNaN('NaN')        //true
    isNaN(NaN)          //true
    isNaN(0 / 0)        //true
    

    A better way to check if the value is really NaN is:

    function is_nan(value) {
        return value != value
    }
    
    is_nan(parseFloat("geoff"))
    
    0 讨论(0)
  • 2020-11-22 06:40

    As of ES6, Object.is(..) is a new utility that can be used to test two values for absolute equality:

    var a = 3 / 'bar';
    Object.is(a, NaN); // true
    
    0 讨论(0)
  • 2020-11-22 06:40

    According to IEEE 754, all relationships involving NaN evaluate as false except !=. Thus, for example, (A >= B) = false and (A <= B) = false if A or B or both is/are NaN.

    0 讨论(0)
  • 2020-11-22 06:41

    You should use the global isNaN(value) function call, because:

    • It is supported cross-browser
    • See isNaN for documentation

    Examples:

     isNaN('geoff'); // true
     isNaN('3'); // false
    

    I hope this will help you.

    0 讨论(0)
  • 2020-11-22 06:43

    Simple Solution!

    REALLY super simple! Here! Have this method!

    function isReallyNaN(a) { return a !== a; };
    

    Use as simple as:

    if (!isReallyNaN(value)) { return doingStuff; }
    

    See performance test here using this func vs selected answer

    Also: See below 1st example for a couple alternate implementations.


    Example:

    function isReallyNaN(a) { return a !== a; };
    
    var example = {
        'NaN': NaN,
        'an empty Objet': {},
        'a parse to NaN': parseFloat('$5.32'),
        'a non-empty Objet': { a: 1, b: 2 },
        'an empty Array': [],
        'a semi-passed parse': parseInt('5a5'),
        'a non-empty Array': [ 'a', 'b', 'c' ],
        'Math to NaN': Math.log(-1),
        'an undefined object': undefined
      }
    
    for (x in example) {
        var answer = isReallyNaN(example[x]),
            strAnswer = answer.toString();
        $("table").append($("<tr />", { "class": strAnswer }).append($("<th />", {
            html: x
        }), $("<td />", {
            html: strAnswer
        })))
    };
    table { border-collapse: collapse; }
    th, td { border: 1px solid; padding: 2px 5px; }
    .true { color: red; }
    .false { color: green; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <table></table>

    There are a couple alternate paths you take for implementaion, if you don't want to use an alternately named method, and would like to ensure it's more globally available. Warning These solutions involve altering native objects, and may not be your best solution. Always use caution and be aware that other Libraries you might use may depend on native code or similar alterations.

    Alternate Implementation 1: Replace Native isNaN method.

    //  Extremely simple. Just simply write the method.
    window.isNaN = function(a) { return a !==a; }
    

    Alternate Implementation 2: Append to Number Object
    *Suggested as it is also a poly-fill for ECMA 5 to 6

    Number['isNaN'] || (Number.isNaN = function(a) { return a !== a });
    //  Use as simple as
    Number.isNaN(NaN)
    

    Alternate solution test if empty

    A simple window method I wrote that test if object is Empty. It's a little different in that it doesn't give if item is "exactly" NaN, but I figured I'd throw this up as it may also be useful when looking for empty items.

    /** isEmpty(varried)
     *  Simple method for testing if item is "empty"
     **/
    ;(function() {
       function isEmpty(a) { return (!a || 0 >= a) || ("object" == typeof a && /\{\}|\[(null(,)*)*\]/.test(JSON.stringify(a))); };
       window.hasOwnProperty("empty")||(window.empty=isEmpty);
    })();
    

    Example:

    ;(function() {
       function isEmpty(a) { return !a || void 0 === a || a !== a || 0 >= a || "object" == typeof a && /\{\}|\[(null(,)*)*\]/.test(JSON.stringify(a)); };
       window.hasOwnProperty("empty")||(window.empty=isEmpty);
    })();
    
    var example = {
        'NaN': NaN,
        'an empty Objet': {},
        'a parse to NaN': parseFloat('$5.32'),
        'a non-empty Objet': { a: 1, b: 2 },
        'an empty Array': new Array(),
        'an empty Array w/ 9 len': new Array(9),
        'a semi-passed parse': parseInt('5a5'),
        'a non-empty Array': [ 'a', 'b', 'c' ],
        'Math to NaN': Math.log(-1),
        'an undefined object': undefined
      }
    
    for (x in example) {
    	var answer = empty(example[x]),
    		strAnswer = answer.toString();
    	$("#t1").append(
    		$("<tr />", { "class": strAnswer }).append(
    			$("<th />", { html: x }),
    			$("<td />", { html: strAnswer.toUpperCase() })
    		)
    	)
    };
    
    
    function isReallyNaN(a) { return a !== a; };
    for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("<tr />",{"class":strAnswer}).append($("<th />",{html:x}),$("<td />",{html:strAnswer.toUpperCase()})))};
    table { border-collapse: collapse; float: left; }
    th, td { border: 1px solid; padding: 2px 5px; }
    .true { color: red; }
    .false { color: green; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <table id="t1"><thead><tr><th colspan="2">isEmpty()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
    <table id="t2"><thead><tr><th colspan="2">isReallyNaN()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>


    Extremely Deep Check If Is Empty

    This last one goes a bit deep, even checking if an Object is full of blank Objects. I'm sure it has room for improvement and possible pits, but so far, it appears to catch most everything.

    function isEmpty(a) {
    	if (!a || 0 >= a) return !0;
    	if ("object" == typeof a) {
    		var b = JSON.stringify(a).replace(/"[^"]*":(0|"0*"|false|null|\{\}|\[(null(,)?)*\]),?/g, '').replace(/"[^"]*":\{\},?/g, '');
    		if ( /^$|\{\}|\[\]/.test(b) ) return !0;
    		else if (a instanceof Array)  {
    			b = b.replace(/(0|"0*"|false|null|\{\}|\[(null(,)?)*\]),?/g, '');
    			if ( /^$|\{\}|\[\]/.test(b) ) return !0;
    		}
    	}
    	return false;
    }
    window.hasOwnProperty("empty")||(window.empty=isEmpty);
    
    var example = {
        'NaN': NaN,
        'an empty Objet': {},
        'a parse to NaN': parseFloat('$5.32'),
        'a non-empty Objet': { a: 1, b: 2 },
        'an empty Array': new Array(),
        'an empty Array w/ 9 len': new Array(9),
        'a semi-passed parse': parseInt('5a5'),
        'a non-empty Array': [ 'a', 'b', 'c' ],
        'Math to NaN': Math.log(-1),
        'an undefined object': undefined,
        'Object Full of Empty Items': { 1: '', 2: [], 3: {}, 4: false, 5:new Array(3), 6: NaN, 7: null, 8: void 0, 9: 0, 10: '0', 11: { 6: NaN, 7: null, 8: void 0 } },
        'Array Full of Empty Items': ["",[],{},false,[null,null,null],null,null,null,0,"0",{"6":null,"7":null}]
      }
    
    for (x in example) {
    	var answer = empty(example[x]),
    		strAnswer = answer.toString();
    	$("#t1").append(
    		$("<tr />", { "class": strAnswer }).append(
    			$("<th />", { html: x }),
    			$("<td />", { html: strAnswer.toUpperCase() })
    		)
    	)
    };
    
    
    function isReallyNaN(a) { return a !== a; };
    for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("<tr />",{"class":strAnswer}).append($("<th />",{html:x}),$("<td />",{html:strAnswer.toUpperCase()})))};
    table { border-collapse: collapse; float: left; }
    th, td { border: 1px solid; padding: 2px 5px; }
    .true { color: red; }
    .false { color: green; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <table id="t1"><thead><tr><th colspan="2">isEmpty()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
    <table id="t2"><thead><tr><th colspan="2">isReallyNaN()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>

    0 讨论(0)
提交回复
热议问题