Comparing NaN values for equality in Javascript

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

提交回复
热议问题