NaN - JavaScript 编辑

The global NaN property is a value representing Not-A-Number.

Property attributes of NaN
Writableno
Enumerableno
Configurableno
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.

Description

NaN is a property of the global object. In other words, it is a variable in global scope.

The initial value of 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, or undefined + undefined)
  • Any operation that involves a string and is not an addition operation (e.g. "foo" / 3)

Examples

Testing against NaN

NaN compares unequal (via ==, !=, ===, and !==) 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

Specifications

Specification
ECMAScript (ECMA-262)
The definition of 'NaN' in that specification.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:140 次

字数:5548

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文