Comparing NaN values for equality in Javascript

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

提交回复
热议问题