Comparing NaN values for equality in Javascript

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

提交回复
热议问题