JavaScript Math.log2() 方法



JavaScript 的 Math.log2() 方法接收一個數值作為引數,並返回該數字的以 2 為底的對數。從數學上講,一個數字 x 的以 2 為底的對數是基數(在本例中為 2)必須提升到哪個次冪才能得到值 x。換句話說,如果 y = Math.log2(x),則 2^y = x。

提供的引數應該大於或等於 0,否則此方法將返回 NaN(非數字)作為結果。

語法

以下是 JavaScript Math.log2() 方法的語法:

Math.log2(x)

引數

此方法只接受一個引數。具體如下:

  • x: 一個正數。

返回值

此方法返回指定數字 x 的以 2 為底的對數。

示例 1

在下面的示例中,我們使用 JavaScript Math.log2() 方法來計算 10 的以 2 為底的對數:

<html>
<body>
<script>
   const result = Math.log2(10);
   document.write(result);
</script>
</body>
</html>
</html>

輸出

執行上述程式後,返回的結果為 3.3219。

示例 2

在這裡,我們檢索數值 1 的以 2 為底的對數:

<html>
<body>
<script>
   const result = Math.log2(1);
   document.write(result);
</script>
</body>
</html>
</html>

輸出

它返回 0 作為 1 的以 2 為底的對數。

示例 3

如果我們將 0 或 -0 作為引數提供給此方法,它將返回 -Infinity 作為結果:

<html>
<body>
<script>
   const result1 = Math.log2(0);
   const result2 = Math.log2(-0);
   document.write(result1, "<br>", result2);
</script>
</body>
</html>
</html>

輸出

正如我們在輸出中看到的,它返回 -Infinity 作為結果。

示例 4

如果提供的引數小於或等於 -1,此方法將返回 NaN 作為結果:

<html>
<body>
<script>
   const result = Math.log2(-3);
   document.write(result);
</script>
</body>
</html>
</html>

輸出

正如我們在輸出中看到的,它返回 NaN 作為結果。

廣告