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

前端 未结 30 2679
伪装坚强ぢ
伪装坚强ぢ 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: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($("", { "class": strAnswer }).append($("", {
            html: x
        }), $("", {
            html: strAnswer
        })))
    };
    table { border-collapse: collapse; }
    th, td { border: 1px solid; padding: 2px 5px; }
    .true { color: red; }
    .false { color: green; }
    
    

    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(
    		$("", { "class": strAnswer }).append(
    			$("", { html: x }),
    			$("", { html: strAnswer.toUpperCase() })
    		)
    	)
    };
    
    
    function isReallyNaN(a) { return a !== a; };
    for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("",{"class":strAnswer}).append($("",{html:x}),$("",{html:strAnswer.toUpperCase()})))};
    table { border-collapse: collapse; float: left; }
    th, td { border: 1px solid; padding: 2px 5px; }
    .true { color: red; }
    .false { color: green; }
    
    
    isEmpty()
    Value TypeBool Return
    isReallyNaN()
    Value TypeBool Return


    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(
    		$("", { "class": strAnswer }).append(
    			$("", { html: x }),
    			$("", { html: strAnswer.toUpperCase() })
    		)
    	)
    };
    
    
    function isReallyNaN(a) { return a !== a; };
    for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("",{"class":strAnswer}).append($("",{html:x}),$("",{html:strAnswer.toUpperCase()})))};
    table { border-collapse: collapse; float: left; }
    th, td { border: 1px solid; padding: 2px 5px; }
    .true { color: red; }
    .false { color: green; }
    
    
    isEmpty()
    Value TypeBool Return
    isReallyNaN()
    Value TypeBool Return

提交回复
热议问题