Math.hypot()
Math.hypot() 靜態方法返回其引數平方和的平方根。即,
試一試
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
語法
Math.hypot()
Math.hypot(value1)
Math.hypot(value1, value2)
Math.hypot(value1, value2, /* …, */ 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()
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 |
瀏覽器相容性
載入中…