Math.log2() 方法返回数字的以 2 为底的对数。在数学中,它等同于 log2(x)。
示例
// calculate the base 2 log of 2
let value= Math.log2(2);
console.log(value)
// Output: 1
log2() 语法
log2() 的语法是
Math.log2(x)
这里,log2() 是一个静态方法。因此,我们需要使用类名 Math 来访问该方法。
log2() 参数
log2() 方法接受
- x - 一个数字
log2() 返回值
log2() 方法返回
- 给定数字的以 2 为底的对数。
- 对于负数和非数字参数,返回
NaN。
示例 1:JavaScript Math.log2()
// find the base 2 log value of 1
var value1 = Math.log2(1);
console.log(value1);
// find the base 2 log value of 8
var value2=Math.log2(8);
console.log(value2)
输出
0 3
在上面的例子中:
Math.log2(1)- 计算 1 的以 2 为底的对数值Math.log2(8)- 计算 8 的以 2 为底的对数值
示例 2:log2() 与 0
// find the base 2 log value of 0
var value = Math.log2(0);
console.log(value);
// Output: -Infinity
在上面的示例中,我们使用了 log2() 方法来计算 0 的以 2 为底的对数值。
输出 -Infinity 表示 0 的以 2 为底的对数值是负无穷大。
示例 3:log2() 与负数
// find the base 2 log value of -1
var value = Math.log2(-1);
console.log(value);
// Output: NaN
在上面的示例中,我们使用了 log2() 方法来计算负数的以 2 为底的对数值。
输出 NaN 表示 Not a Number(非数字)。我们得到这个结果是因为负数的以 2 为底的对数值是未定义的。
另请阅读