JavaScript Math.log2() 方法
JavaScript Math.log2() 方法接受一个数值作为参数,并返回该数值以 2 为底的对数。从数学上讲,数字 x 以 2 为底的对数是要得到 x 的值,必须对底数(在本例中为 2)求幂。换句话说,如果 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 作为参数,则返回负无穷大的结果 -
<html> <body> <script> const result1 = Math.log2(0); const result2 = Math.log2(-0); document.write(result1, "<br>", result2); </script> </body> </html> </html>
输出
正如我们在输出中看到的,它返回了负无穷大的结果。
示例 4
如果提供的参数小于或等于 -1,则此方法返回 NaN 作为结果 -
<html> <body> <script> const result = Math.log2(-3); document.write(result); </script> </body> </html> </html>
输出
正如我们在输出中看到的,它返回了 NaN 作为结果。

