1. 程式人生 > >Number.isNaN() 和isNaN(),還有Number.NaN的比較

Number.isNaN() 和isNaN(),還有Number.NaN的比較

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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