Math.hypot()

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

Math.hypot() 静态方法返回其参数平方和的平方根。即,

Math.hypot(v1,v2,,vn)=i=1nvi2=v12+v22++vn2\mathtt{\operatorname{Math.hypot}(v_1, v_2, \dots, v_n)} = \sqrt{\sum_{i=1}^n v_i^2} = \sqrt{v_1^2 + v_2^2 + \dots + v_n^2}

试一试

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

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

console.log(Math.hypot(3, 4, 5));
// Expected output: 7.0710678118654755

console.log(Math.hypot(-5));
// Expected output: 5

语法

js
Math.hypot()
Math.hypot(value1)
Math.hypot(value1, value2)
Math.hypot(value1, value2, /* …, */ valueN)

参数

value1, …, valueN

数字。

返回值

给定参数的平方和的平方根。如果任何参数是 ±Infinity,则返回 Infinity。否则,如果至少有一个参数是 NaN 或被转换为 NaN,则返回 NaN。如果没有给出参数或所有参数都是 ±0,则返回 0

描述

计算直角三角形的斜边或复数的模,使用公式 Math.sqrt(v1*v1 + v2*v2),其中 v1 和 v2 是三角形的直角边长度,或复数的实部和虚部。2 维或更高维度的相应距离可以通过在平方根下添加更多平方来计算:Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4)

此函数使此计算更轻松、更快速;您可以调用 Math.hypot(v1, v2),或 Math.hypot(v1, /* …, */, vN)

如果数字的模非常大,Math.hypot 还可以避免溢出/下溢问题。JS 中可表示的最大数字是 Number.MAX_VALUE,约为 10308。如果您的数字大于约 10154,则对它们求平方将导致 Infinity。例如,Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity。如果您改用 hypot(),您会得到一个更好的结果:Math.hypot(1e200, 1e200) = 1.4142...e+200。对于非常小的数字也一样。Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0,但 Math.hypot(1e-200, 1e-200) = 1.4142...e-200

当有一个参数时,Math.hypot() 等同于 Math.abs()Math.hypot.length 为 2,这表明它被设计为至少处理两个参数。

因为 hypot()Math 的静态方法,所以您总是将其用作 Math.hypot(),而不是作为您创建的 Math 对象的实例方法(Math 不是构造函数)。

示例

使用 Math.hypot()

js
Math.hypot(3, 4); // 5
Math.hypot(3, 4, 5); // 7.0710678118654755
Math.hypot(); // 0
Math.hypot(NaN); // NaN
Math.hypot(NaN, Infinity); // Infinity
Math.hypot(3, 4, "foo"); // NaN, since +'foo' => NaN
Math.hypot(3, 4, "5"); // 7.0710678118654755, +'5' => 5
Math.hypot(-3); // 3, the same as Math.abs(-3)

规范

规范
ECMAScript® 2026 语言规范
# sec-math.hypot

浏览器兼容性

另见