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 作为结果。

广告
© . All rights reserved.