Comparing NaN values for equality in Javascript

前端 未结 12 1726
猫巷女王i
猫巷女王i 2020-12-13 08:19

I need to compare two numeric values for equality in Javascript. The values may be NaN as well. I\'ve come up with this code:

if (val1 == val2 |         


        
相关标签:
12条回答
  • 2020-12-13 08:53

    Avoid isNaN. Its behaviour is misleading:

    isNaN(undefined) // true
    

    _.isNaN (from Underscore.js) is an elegant function which behaves as expected:

    // Is the given value `NaN`?
    // 
    // `NaN` is the only value for which `===` is not reflexive.
    _.isNaN = function(obj) {
      return obj !== obj;
    };
    
    _.isNaN(undefined) // false
    _.isNaN(0/0) // true
    
    0 讨论(0)
  • 2020-12-13 08:53

    NaN is never equal to itself no matter the comparison method, so the only more concise solution for your problem that I can think of would be to create a function call with a descriptive name for doing this rather special comparison and use that comparison function in your code instead.

    That would also have the advantage of localizing changes to the algorithm the day you decide that undefined should be equal to undefined too.

    0 讨论(0)
  • 2020-12-13 08:53

    Why not an if statement like this?

    if (isNaN(x) == true){
            alert("This is not a number.");
        }
    
    0 讨论(0)
  • 2020-12-13 08:53

    Found another way using Array.prototype.includes MDN link. Apparently, [NaN].includes(NaN) returns true for NaN.

    function IsActuallyNaN(obj) {
      return [obj].includes(NaN);  
    }
    

    Or we can go with davidchambers' solution which is much simpler.

    function IsActuallyNaN2(obj) {
      return obj !== obj;
    }
    
    0 讨论(0)
  • 2020-12-13 08:55

    Try using Object.is(), it determines whether two values are the same value. Two values are the same if one of the following holds:

    • both undefined
    • both null
    • both true or both false
    • both strings of the same length with the same characters in the same order
    • both the same object
    • both numbers and
      • both +0
      • both -0
      • both NaN
      • or both non-zero and both not NaN and both have the same value

    e.g. Object.is(NaN, NaN) => true

    Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is

    0 讨论(0)
  • 2020-12-13 09:01

    As long as you know these two variables are numeric, you can try:

    if (val1 + '' == val2 + '')
    

    It turns the two values into strings. A funny answer, but it should work. :)

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