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

浏览器兼容性

另见