JavaScript Math.hypot() 方法
JavaScript 中的 Math.hypot() 方法接受一个或多个数字作为参数,并计算其参数平方和的平方根。该方法通常用于计算坐标系中两点之间的欧氏距离。
如果任何参数为 Infinity,则此方法返回"Infinity"。如果至少有一个参数为 NaN,则返回 NaN。如果没有提供参数或所有参数均为 0,则返回 0。
语法
以下是 JavaScript Math.hypot() 方法的语法 -
Math.hypot(value1, value2, ..., valueN)
参数
此方法接受一个或多个数字作为参数。
- value1:一个数值。
- value2:一个数值,依此类推。
返回值
此方法返回所提供参数平方和的平方根。
示例 1
在示例中, Math.hypot(5, 12) 计算边长分别为 5 和 12 的直角三角形的斜边。
<html> <body> <script> const result = Math.hypot(5, 12); document.write(result); </script> </body> </html>
输出
执行上述程序后,斜边的值为 13。
示例 2
此处,Math.hypot(1, 2, 3) 计算三维空间中的欧氏距离。它求三个值 (1, 2, 3) 平方和的平方根 -
<html> <body> <script> const result = Math.hypot(1, 2, 3); document.write(result); </script> </body> </html>
输出
如果我们执行上述程序,它将返回大约 3.74。
示例 3
如果我们提供字符串值作为参数,则此方法返回 NaN 作为结果 -
<html>
<body>
<script>
const result = Math.hypot("Tutotrialspoint", "Tutorix");
document.write(result);
</script>
</body>
</html>
输出
正如我们在输出中看到的,它返回了 NaN 作为结果。
示例 4
如果我们提供 Infinity 作为参数,则此方法返回 Infinity 作为结果 -
<html> <body> <script> const result = Math.hypot(Infinity); document.write(result); </script> </body> </html>
输出
正如我们在输出中看到的,它返回的结果为 Infinity。
示例 5
如果没有提供参数或所有参数均为 0,则此方法返回的结果为 0 −
<html> <body> <script> const result1 = Math.hypot(); const result2 = Math.hypot(0); document.write(result1, "<br>", result2); </script> </body> </html>
输出
正如我们在输出中看到的,两种情况下的结果都为 0。

