Comparing NaN values for equality in Javascript

前端 未结 12 1753
猫巷女王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
    

提交回复
热议问题