全域屬性 NaN 表示「非數值」(Not-A-Number)的數值。

Property attributes of NaN
Writable no
Enumerable no
Configurable no

語法

NaN

描述

NaN 的屬性屬於全域物件

如同 Number.NaN 一般,NaN 的初始數值是「非數值」。在當今的瀏覽器中,NaN 屬性不可設定(non-configurable)也不可覆寫(non-writable)。雖然可能有例外,也請不要覆蓋它。

寫程式很少會直接動用 NaN。通常是在 Math 函式計算失敗(Math.sqrt(-1))或函式解析數字失敗(parseInt("blabla"))後才會回傳。

偵測是否為 NaN

NaN 不等於(==!====!==)任何值,包括 NaN 本身。請使用 Number.isNaN()isNaN() 來確認某個數值是否為 NaN。Or perform a self-comparison: NaN, and only NaN, will compare unequal to itself.

NaN === NaN;        // false
Number.NaN === NaN; // false
isNaN(NaN);         // true
isNaN(Number.NaN);  // true

function valueIsNaN(v) { return v !== v; }
valueIsNaN(1);          // false
valueIsNaN(NaN);        // true
valueIsNaN(Number.NaN); // true

但請注意 isNaN()Number.isNaN() 之間是有區別的:前者會在目前數字是 NaN 的時候回傳 true,或在裡面包藏一個號碼後變成 NaN;而後者,只有在數值是 NaN 的時候才會回傳 true

規範

規範 狀態 註解
ECMAScript 1st Edition (ECMA-262) Standard 初始定義。JavaScript 1.3 導入
ECMAScript 5.1 (ECMA-262)
The definition of 'NaN' in that specification.
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'NaN' in that specification.
Standard  
ECMAScript Latest Draft (ECMA-262)
The definition of 'NaN' in that specification.
Draft  

瀏覽器相容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung InternetNode.js
Basic supportChrome Full support YesEdge Full support YesFirefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes

Legend

Full support  
Full support

參見

文件標籤與貢獻者

此頁面的貢獻者: iigmir, jackblackevo
最近更新: iigmir,