Math.log2()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Math.log2() 靜態方法返回一個數字的以 2 為底的對數。即:

x>0,𝙼𝚊𝚝𝚑.𝚕𝚘𝚐𝟸(𝚡)=log2(x)=唯一y使得2y=x\forall x > 0,\;\mathtt{\operatorname{Math.log2}(x)} = \log_2(x) = \text{唯一滿足 } 2^y = x \text{ 的 } y

試一試

console.log(Math.log2(3));
// Expected output: 1.584962500721156

console.log(Math.log2(2));
// Expected output: 1

console.log(Math.log2(1));
// Expected output: 0

console.log(Math.log2(0));
// Expected output: -Infinity

語法

js
Math.log2(x)

引數

x

大於或等於 0 的數字。

返回值

x 的以 2 為底的對數。如果 x < 0,則返回 NaN

描述

因為 log2()Math 的一個靜態方法,所以你總是使用 Math.log2() 來呼叫它,而不是作為你建立的 Math 物件的某個方法來呼叫(Math 不是一個建構函式)。

此函式等同於 Math.log(x) / Math.log(2)。對於 log2(e),請使用常量 Math.LOG2E,它等於 1 / Math.LN2

示例

使用 Math.log2()

js
Math.log2(-2); // NaN
Math.log2(-0); // -Infinity
Math.log2(0); // -Infinity
Math.log2(1); // 0
Math.log2(2); // 1
Math.log2(3); // 1.584962500721156
Math.log2(1024); // 10
Math.log2(Infinity); // Infinity

規範

規範
ECMAScript® 2026 語言規範
# sec-math.log2

瀏覽器相容性

另見