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>
输出
如果我们执行上述程序,hypotenuse 的值将为 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 作为结果。