Math.sqrt()

Baseline 已廣泛支援

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

Math.sqrt() 靜態方法返回數字的平方根。即

x0,Math.sqrt(𝚡)=x=唯一y0使得y2=x\forall x \geq 0,\;\mathtt{\operatorname{Math.sqrt}(x)} = \sqrt{x} = \text{the unique } y \geq 0 \text{ such that } y^2 = x

試一試

function calcHypotenuse(a, b) {
  return Math.sqrt(a * a + b * b);
}

console.log(calcHypotenuse(3, 4));
// Expected output: 5

console.log(calcHypotenuse(5, 12));
// Expected output: 13

console.log(calcHypotenuse(0, 0));
// Expected output: 0

語法

js
Math.sqrt(x)

引數

x

大於或等於 0 的數字。

返回值

x 的平方根,一個非負數。如果 x < 0,則返回 NaN

描述

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

示例

使用 Math.sqrt()

js
Math.sqrt(-1); // NaN
Math.sqrt(-0); // -0
Math.sqrt(0); // 0
Math.sqrt(1); // 1
Math.sqrt(2); // 1.414213562373095
Math.sqrt(9); // 3
Math.sqrt(Infinity); // Infinity

規範

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

瀏覽器相容性

另見