Comparing NaN values for equality in Javascript

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

    Equality comparison with NaN always results in False.

    We can go for the javascript function isNaN() for checking equality with NaN. Example:

    1. isNaN(123) //false
    
    2. var array = [3, NaN];
    
    for(var i = 0 ; i< array.length; i++){
      if(isNaN(array[i])){
          console.log("True ---- Values of " + i);
        } else {
          console.log("false ---- Values of " + i);
        }
    }
    

    Results:

    false ---- Values of 0

    True ---- Values of 1

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

    For Numeric cases the solution is fine but to extend it to work for other data-types as well my suggestion would be as follows:

    if(val1 === val2 || (val1 !== val1 && val2 !== val2))
    

    Reason being global isNaN is erroneous. It will give you wrong results in scenarios like

    isNaN(undefined); // true
    isNaN({});        // true
    isNaN("lorem ipsum"); // true 
    

    I have posted a comprehensive answer here which covers the NaN comparison for equality as well.

    How to test if a JavaScript variable is NaN

    0 讨论(0)
  • 2020-12-13 08:43
    if(val1 == val2 || (isNaN(val1) && isNaN(val2)))
    

    Nothing to improve. Just add the parentheses to make it clear to everyone.

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

    And what's about the function Number.isNaN() ? I believe this must be used whenever is possible.

    > NaN === NaN
    false
    > Number.isNaN
    ƒ isNaN() { [native code] }
    > Number.isNaN() === Number.isNaN()
    true
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN

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

    if ( val1 === val2 )

    If either one or both are NaN it will evaluate to false.

    Also, NaN !== NaN

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

    I created this answer after reviewing the suggestions of ThiefMaster, Esailija, Joachim Isaksson and davidchambers. Can this be further improved?

    // Determines if two numeric values are equal.
    // Also returns true when both parameters are NaN.
    function areEqualNumeric(val1, val2) {
        return val1 === val2 || (val1 !== val1 && val2 !== val2);
    }
    
    0 讨论(0)
提交回复
热议问题