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.7 和 2.4 的平方和的平方根。Math.hypot(7, 24, 25)
计算 7、24 和 25 的平方和的平方根。
示例 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。
另请阅读