The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone
https://github.com/mdn/interactive-examples
and send us a pull request.
描述
NaN
是特性在
全局对象
. In other words, it is a variable in global scope.
初始值
NaN
is Not-A-Number — the same as the value of
Number.NaN
. In modern browsers,
NaN
is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it. It is rather rare to use
NaN
in a program.
There are five different types of operations that return
NaN
:
-
Number cannot be parsed (e.g.
parseInt("blabla")
or
Number(undefined)
)
-
Math operation where the result is not a real number (e.g.
Math.sqrt(-1)
)
-
Operand of an argument is
NaN
(e.g.
7 ** NaN
)
-
Indeterminate form (e.g.
0 * Infinity
)
-
Any operation that involves a string and is not an addition operation (e.g.
"foo" / 3
)
范例
Testing against
NaN
NaN
compares unequal (via
==
,
!=
,
===
,和
!==
) to any other value -- including to another
NaN
value. Use
Number.isNaN()
or
isNaN()
to most clearly determine whether a value is
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
Number.isNaN(NaN); // true
function valueIsNaN(v) { return v !== v; }
valueIsNaN(1); // false
valueIsNaN(NaN); // true
valueIsNaN(Number.NaN); // true
However, do note the difference between
isNaN()
and
Number.isNaN()
: the former will return
true
if the value is currently
NaN
, or if it is going to be
NaN
after it is coerced to a number, while the latter will return
true
only if the value is currently
NaN
:
isNaN('hello world'); // true
Number.isNaN('hello world'); // false
Additionally, some array methods cannot find
NaN
, while others can.
let arr = [2, 4, NaN, 12];
arr.indexOf(NaN); // -1 (false)
arr.includes(NaN); // true
arr.findIndex(n => Number.isNaN(n)); // 2
规范
浏览器兼容性
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out
https://github.com/mdn/browser-compat-data
and send us a pull request.
更新 GitHub 上的兼容性数据
|
Desktop
|
Mobile
|
Server
|
|
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Android webview
|
Chrome for Android
|
Firefox for Android
|
Opera for Android
|
Safari on iOS
|
Samsung Internet
|
Node.js
|
NaN
|
Chrome
1
|
Edge
12
|
Firefox
1
|
IE
4
|
Opera
4
|
Safari
1
|
WebView Android
1
|
Chrome Android
18
|
Firefox Android
4
|
Opera Android
10.1
|
Safari iOS
1
|
Samsung Internet Android
1.0
|
nodejs
0.1.100
|
图例
-
完整支持
完整支持
另请参阅