对属性NaN的理解纠正和对Number.isNaN() 、isNaN()方法的辨析

1.属性NaN的误解纠正

NaN (Not a Number)在w3c 中定义的是非数字的特殊值 ,它的对象是Number所以并不是任何非数字类型的值都会等于NaN,只有在算术运算或数据类型转换出错时是NaN【说明某些算术运算(如求负数的平方根)的结果不是数字。方法 parseInt() 和 parseFloat() 在不能解析指定的字符串时就返回这个值NaN。对于一些常规情况下返回有效数字的函数,也可以采用这种方法,用 Number.NaN 说明它的错误情况】。NaN 与其他数值进行比较的结果总是不相等的,包括它自身在内,不能用==、===判断,只能调用 isNaN() 来比较

eg

(

The fact that NaN means Not a Number does not mean that anything that is not a number is a NaN.

NaN is a special value on floating point arithmethic that represents an undefined result of an operation.

)

2.Number.isNaN() 、isNaN()方法的辨析(Number.isNaN() is different from the global isNaN() function. )

坑:((NaN是javascript的一个坑,非数字字符串转为数字类型时返回NaN,按理说字符串不是数字类型用isNaN()应该返回false的却返回true,所以isNaN()还在坑里),Number.isNaN()纠正了bug)

(

The global isNaN() function converts the tested value to a Number, then tests it.【

If value can not convert to Number, return true.
else If number arithmethic result  is NaN, return true.
Otherwise, return false.

】全局方法isNaN()会先将参数转为Number 类型,在判断是否为NaN ,所以在类型转换失败或运算错误时值为NaN,返回true,其他全为false

Number.isNan() does not convert the values to a Number, and will  return false for any value that is not of the type Number【

If Type(number) is not Number, return false.
If number is NaN, return true.
Otherwise, return false.

Number.isNaN()先判断参数类型,在参数为Number的前提下运算错误时值为NaN返回true,其他全为false

Tip: In JavaScript, the value NaN is considered a type of number.

)

Number.isNaN()要和全局方法isNaN()一样可以使用parseInt或pareseFloat()先进行类型转换

 

3.易错混淆实例

isNaN(NaN);       // true
isNaN(undefined); // true
isNaN({});        // true

isNaN(true);      // false
isNaN(null);      // false
isNaN(1);         // false

isNaN("1");            // fales "1" 被转化为数字 1,因此返回false
isNaN("SegmentFault"); // true "SegmentFault" 被转化成数字 NaN
Number.isNaN('0/0') //string not number false
isNaN('0/0') //arithmethic ilegal (NaN) true
Number.isNaN('123') //string not number false
isNaN('123') //convert to number false
Number.isNaN('Hello') //string not number false
isNaN('Hello') //convert fail(NaN) true
Number.isNaN('') /isNaN(null) //string not number false
Number.isNaN(true) //bool not number false
isNaN('') /isNaN(null) //convert to 0 false
isNaN(true) //convert to 1 false
Number.isNaN(undefined) //undefined not number flase
isNaN(undefined) //convert fail true

//convert fail true
isNaN(parseInt(undefined))
isNaN(parseInt(null))
isNaN(parseInt(''))
isNaN(parseInt(true))

Number.isNaN('NaN') //false
isNaN('NaN') //true
Number.isNaN(NaN) //true
isNaN(NaN) //true

  

 

总结:给我的感觉,在实际运用中 isNaN()用于判断是否为数字 Number.isNaN()用于判断是否运算合法,因此一般使用中都用的是全局的isNaN,把握这两个方法时重点在其算法逻辑(第二点:是先进行类型转化还是先进行类型判断

原文地址:https://www.cnblogs.com/Spring-Rain/p/5722594.html