JavaScript Number isInteger() 方法



JavaScript Number isInteger() 方法是一個靜態方法,用於確定傳遞的值是否為整數。如果傳遞的值是整數,則返回布林值“true”。否則,返回“false”。

在數學中,整數是完整的數字,可以是正數、負數或零,例如 {1, 2, 3, 4, ..., 0, -1, -2, -3, ...}。

語法

以下是 JavaScript Number isInteger() 方法的語法:

Number.isInteger(value)

引數

此方法接受一個名為“value”的引數,如下所述:

  • value − 要檢查是否為整數的值。

返回值

如果傳遞的值是整數,則此方法返回“true”;否則返回“false”。

示例 1

如果我們將正數傳遞給此方法,它將返回“true”。

在下面的程式中,我們使用isInteger()方法來確定傳遞的值“10”是否為整數。

<html>
<head>
<title>JavaScript isInteger() Method</title>
</head>
<body>
<script>
   let num = 10;
   document.write("Is number ", num, " is an Integer? ", Number.isInteger(num));
</script>
</body>
</html>

輸出

上面提到的程式為值 10 返回布林值“true”,如下所示:

Is number 10 is an Integer? true

示例 2

如果我們將null作為引數傳遞給此方法,它將返回“false”。

以下是isInteger()方法的另一個示例。我們將“null”作為引數傳遞給此方法,以檢查它是否為整數。

<html>
<head>
<title>JavaScript isInteger() Method</title>
</head>
<body>
<script>
   let val = null;
   document.write("Is '", val, "' is an Integer? ", Number.isInteger(val));
</script>
</body>
</html>

輸出

執行上述程式後,它將在輸出中返回“false”,如下所示:

Is 'null' is an Integer? false

示例 3

讓我們將0(零)作為引數傳遞給'isInteger()'方法,以驗證它是否為整數。

<html>
<head>
<title>JavaScript isInteger() Method</title>
</head>
<body>
<script>
   let val = 0;
   document.write("Is '", val, "' is an Integer? ", Number.isInteger(val));
</script>
</body>
</html>

輸出

上述程式為值 0 返回“true”,如下所示:

Is '0' is an Integer? true

示例 4

以下示例演示了isInteger()方法的使用。

<html>
<head>
<title>JavaScript isInteger() Method</title>
</head>
<body>
<script>
   document.write("Is the result of 15/0 is an Inetger? ", Number.isInteger(10/0));
</script>
</body>
</html>

輸出

( 15/0 ) 的結果是“infinity”,因此上述程式為此值的返回結果返回“false”,如下所示:

Is the result of 15/0 is an Inetger? false

示例 5

以下示例將演示 JavaScript Number isInteger() 方法的即時用法。

<html>
<head>
<title>JavaScript isInteger() Method</title>
</head>
<body>
<script>
   //declaring function
   function print(x, y){
      if(Number.isInteger(x/y)){
         document.write("Ok")
      }
      else{
         document.write("Not ok");
      }
   }
   let x = 10;
   let y = 5;
   document.write("x = ", x);
   document.write("<br> y = ", y);
   //call the function
   document.write("<br>Result1 = ")
   print(x, y);
   //output will be 'Ok', 

   let n1 = 14.5
   let n2 = 5;
   document.write("<br> n1 = ", n1);
   document.write("<br> n2 = ", n2);
   //call the function
   document.write("<br>Result2 = ")
   print(n1, n2);
   //output will be 'Not ok', because decimal number can't be consider as an integer value
</script>
</body>
</html>

輸出

該程式根據指定的條件顯示語句“Ok”和“Not ok”。

x = 10
y = 5
Result1 = Ok
n1 = 14.5
n2 = 5
Result2 = Not ok
廣告