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,把握這兩個方法時重點在其算法邏輯(第二點:是先進行類型轉化還是先進行類型判斷)