Number.isNaN() - JavaScript 编辑
The Number.isNaN()
method determines whether the passed value is NaN
and its type is Number
. It is a more robust version of the original, global isNaN()
.
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.
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.Syntax
Number.isNaN(value)
Parameters
value
- The value to be tested for
NaN
.
Return value
true if the given value is NaN
and its type is Number
; otherwise, false.
Description
Due to both equality operators, ==
and ===
, evaluating to false
when checking if NaN
is NaN
, the function Number.isNaN()
has become necessary. This situation is unlike all other possible value comparisons in JavaScript.
In comparison to the global isNaN()
function, Number.isNaN()
doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to NaN
, but aren't actually the same value as NaN
. This also means that only values of the type number, that are also NaN
, return true
.
Examples
Using isNaN
Number.isNaN(NaN); // true
Number.isNaN(Number.NaN); // true
Number.isNaN(0 / 0); // true
// e.g. these would have been true with global isNaN()
Number.isNaN('NaN'); // false
Number.isNaN(undefined); // false
Number.isNaN({}); // false
Number.isNaN('blabla'); // false
// These all return false
Number.isNaN(true);
Number.isNaN(null);
Number.isNaN(37);
Number.isNaN('37');
Number.isNaN('37.37');
Number.isNaN('');
Number.isNaN(' ');
Polyfill
The following works because NaN is the only value in JavaScript which is not equal to itself.
Number.isNaN = Number.isNaN || function isNaN(input) {
return typeof input === 'number' && input !== input;
}
Specifications
Specification |
---|
ECMAScript (ECMA-262) The definition of 'Number.isnan' in that specification. |
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论