Number.isNaN()
Number.isNaN()
静态方法判断传入的值是否为数值 NaN
,如果输入不是 Number 类型则返回 false
。它是原始全局 isNaN()
函数的更强大的版本。
¥The Number.isNaN()
static method determines whether the passed value is the number value NaN
, and returns false
if the input is not of the Number type. It is a more robust version of the original, global isNaN()
function.
Try it
语法
参数
返回值
描述
¥Description
函数 Number.isNaN()
提供了一种检查与 NaN
是否相等的便捷方法。请注意,你无法使用 ==
或 ===
运算符来测试与 NaN
是否相等,因为与 JavaScript 中的所有其他值比较不同,每当一个操作数为 NaN
时,即使另一个操作数也是 NaN
,这些操作也会计算为 false
。
¥The function Number.isNaN()
provides a convenient way to check for equality with NaN
. Note that you cannot test for equality with NaN
using either the ==
or ===
operators, because unlike all other value comparisons in JavaScript, these evaluate to false
whenever one operand is NaN
, even if the other operand is also NaN
.
由于在所有可能的 JavaScript 值中,x !== x
仅适用于 NaN
,因此 Number.isNaN(x)
也可以替换为 x !== x
的测试,尽管后者可读性较差。
¥Since x !== x
is only true for NaN
among all possible JavaScript values, Number.isNaN(x)
can also be replaced with a test for x !== x
, despite the latter being less readable.
与全局 isNaN()
函数相反,Number.isNaN()
方法不会将参数强制转换为数字。这使得传递通常会转换为 NaN
但实际上与 NaN
不同的值变得安全。这也意味着只有同样是 NaN
的 Number 类型值才会返回 true
。
¥As opposed to the global isNaN()
function, the Number.isNaN()
method doesn't force-convert the parameter to a number. This makes it 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 Number type that are also NaN
return true
.
示例
使用 isNaN()
Number.isNaN() 和全局 isNaN() 之间的区别
¥Difference between Number.isNaN() and global isNaN()
Number.isNaN()
不会尝试将参数转换为数字,因此非数字始终返回 false
。以下均为 false
:
¥Number.isNaN()
doesn't attempt to convert the parameter to a number, so non-numbers always return false
. The following are all false
:
Number.isNaN("NaN");
Number.isNaN(undefined);
Number.isNaN({});
Number.isNaN("blabla");
Number.isNaN(true);
Number.isNaN(null);
Number.isNaN("37");
Number.isNaN("37.37");
Number.isNaN("");
Number.isNaN(" ");
全局 isNaN()
将其参数强制为数字:
¥The global isNaN()
coerces its parameter to a number:
isNaN("NaN"); // true
isNaN(undefined); // true
isNaN({}); // true
isNaN("blabla"); // true
isNaN(true); // false, this is coerced to 1
isNaN(null); // false, this is coerced to 0
isNaN("37"); // false, this is coerced to 37
isNaN("37.37"); // false, this is coerced to 37.37
isNaN(""); // false, this is coerced to 0
isNaN(" "); // false, this is coerced to 0
规范
Specification |
---|
ECMAScript Language Specification # sec-number.isnan |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also