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) 计算 3D 空间中的欧几里得距离。它找到三个值 (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 作为结果。

广告

© . All rights reserved.