JavaScript Number NaN 是一个静态属性,表示一个 Not-A-Number 的值。因为它是 Number 对象的静态属性,所以您可以使用 Number.NaN 直接访问它,而不是作为变量的属性。
如果你尝试使用变量 x.NaN 来访问这个属性,其中 'x' 是一个变量,你会得到 'undefined' 作为结果。这是因为 NaN 是 Number 对象的静态属性,而不是单个变量的属性。
语法
以下是 JavaScript Number NaN 属性的语法 -
Number.NaN
参数
它不接受任何参数。
返回值
此属性没有任何返回值。
示例 1
下面的程序演示了 Number.NaN 属性的用法。
<html>
<head>
<title>JavaScript Number NaN Property</title>
</head>
<body>
<script>
document.write("Result = ", Number.NaN);
</script>
</body>
</html>
输出
上述程序在输出中返回 'NaN'。
Result = NaN
示例 2
如果你尝试使用变量而不是 Number 对象来访问这个属性,你会得到 'undefined' 作为结果。
<html>
<head>
<title>JavaScript Number NaN Property</title>
</head>
<body>
<script>
let x = 10;
document.write("x = ", x);
document.write("<br>x.NaN is = ", x.NaN);
</script>
</body>
</html>
输出
上面的程序显示 'undefined',因为变量无法访问 'NaN' 属性。
x = 10
x.NaN is = undefined
x.NaN is = undefined
示例 3
以下程序检查一个数字,如果它不是有效数字,则返回 Number.NaN;否则,它将显示 “passed”。
<html>
<head>
<title>JavaScript Number NaN Property</title>
</head>
<body>
<script>
function check(x){
if(isNaN(x)){
return Number.NaN;
}
else{
return x + " is a number...!";
}
}
let x = 10;
document.write("x = ", x);
document.write("<br>Result1 = ", check(x));
let y = NaN;
document.write("<br>y = ", y);
document.write("<br>Result2 = ", check(y));
</script>
</body>
</html>
输出
上述程序根据条件显示输出(对于 true,则为 Number.NaN;对于 false,将返回一个语句)。
x = 10
Result1 = 10 is a number...!
y = NaN
Result2 = NaN
Result1 = 10 is a number...!
y = NaN
Result2 = NaN