JavaScript Number NaN 屬性



JavaScript Number NaN 是一個靜態屬性,表示非數字的值。因為它 是 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

示例 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
廣告