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() 方法来计算以 2 为基数的对数 10 -
<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 作为结果。