JavaScript Math.hypot()

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

示例

// the square root of the sum of 3 and 4 var num = Math.hypot(3, 4);
console.log(num); // 5

hypot() 语法

hypot() 方法的语法是:

Math.hypot(n1, n2, ..., nx)

在这里,hypot() 是一个静态方法。因此,我们需要使用类名 Math 来访问该方法。


hypot() 参数

hypot() 方法接受任意数量(一个或多个)的数字作为参数。

  • n1 - 一个数字
  • n2 - 一个数字,依此类推。

hypot() 返回值

hypot() 方法返回:

  • 给定参数的平方和的平方根。
  • 如果任何参数为非数字,则返回 NaN
  • 如果没有给出参数,则返回 0

示例 1:JavaScript Math.hypot()

// the square root of the sum of 0.7 and 2.4 var num1 = Math.hypot(0.7, 2.4);
console.log(num1); // 2.5
// the square root of the sum of 7, 24, and 25 var num2 = Math.hypot(7, 24, 25);
console.log(num2); // 35.35533905932738

在上面的例子中:

  • Math.hypot(0.7, 2.4) 计算 0.72.4 的平方和的平方根。
  • Math.hypot(7, 24, 25) 计算 72425 的平方和的平方根。

示例 2:带单个参数的 hypot()

// the square root of the sum of squares of -3 var num = Math.hypot(-3);
console.log(num); // 3

在上面的示例中,我们使用 Math.hypot() 计算 -3 的平方和的平方根。

输出 3 表明对于单值参数,会返回它们的绝对值。


示例 3:不带参数的 hypot()

// call hypot() without passing any arguments var num = Math.hypot();
console.log(num); // 0

在上面的示例中,我们使用 Math.hypot() 在不传递任何参数的情况下计算平方根。

输出表明,如果不传递任何参数,则返回 0


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战