Comparing NaN values for equality in Javascript

前端 未结 12 1766
猫巷女王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条回答
  •  猫巷女王i
    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.

提交回复
热议问题