Skip to content

Instantly share code, notes, and snippets.

@jialinhuang00
Created October 31, 2017 14:38
Show Gist options
  • Save jialinhuang00/c3d66f661bd4f022ab68ec9bc8c3403a to your computer and use it in GitHub Desktop.
Save jialinhuang00/c3d66f661bd4f022ab68ec9bc8c3403a to your computer and use it in GitHub Desktop.
dig deeper for isNaN()
※ NaN === NaN --> false
※ isNaN(NaN) --> true
※ typeof NaN --> 'number'
※ isNaN(x)、isNaN(x - 0)、isNaN(Number(x))、Number.isNaN(x - 0)、Number.isNaN(Number(x))都是一樣的東西
一、false狀況下:
1. 的確是數字
0, -1.2, Infinity, ...
2. 不是數字,但可透過算術表達成數字
'', [], new String(), new Array(), '0', null, false
--> 都轉換成0
'Infinity'
--> Infinity
true
--> 1
二、true狀況下:
String, Array, 'strugewji', 0/0, '0/0', Infinity/Infinity, NaN, undefined, (沒傳入)
三、但明明是要測試是否Not A Number,isNaN會試著轉換成數字Number(x)來判斷NaN。
武斷地因「字串轉換數字失敗」判斷true也過於撈過界。所以要真正的測試是否NaN可以這樣寫:
function isRealNaN(value) {
return value !== value;
}
以NaN !== NaN的奇怪特性來寫出條件。
這樣一來二、true狀況下:'strugewji', undefined這兩項就會回傳false了。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment