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

前端 未结 30 2951
伪装坚强ぢ
伪装坚强ぢ 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:44

    To fix the issue where '1.2geoff' becomes parsed, just use the Number() parser instead.

    So rather than this:

    parseFloat('1.2geoff'); // => 1.2
    isNaN(parseFloat('1.2geoff')); // => false
    isNaN(parseFloat('.2geoff')); // => false
    isNaN(parseFloat('geoff')); // => true
    

    Do this:

    Number('1.2geoff'); // => NaN
    isNaN(Number('1.2geoff')); // => true
    isNaN(Number('.2geoff')); // => true
    isNaN(Number('geoff')); // => true
    

    EDIT: I just noticed another issue from this though... false values (and true as a real boolean) passed into Number() return as 0! In which case... parseFloat works every time instead. So fall back to that:

    function definitelyNaN (val) {
        return isNaN(val && val !== true ? Number(val) : parseFloat(val));
    }
    

    And that covers seemingly everything. I benchmarked it at 90% slower than lodash's _.isNaN but then that one doesn't cover all the NaN's:

    http://jsperf.com/own-isnan-vs-underscore-lodash-isnan

    Just to be clear, mine takes care of the human literal interpretation of something that is "Not a Number" and lodash's takes care of the computer literal interpretation of checking if something is "NaN".

提交回复
热议问题