概述

Math.hypot() 函数返回它的所有参数的平方和的平方根,即:

Math.hypot(v1,v2,,vn)=i=1nvi2=v12+v22++vn2\mathtt{\operatorname{Math.hypot}(v_1, v_2, \dots, v_n)} = \sqrt{\sum_{i=1}^n v_i^2} = \sqrt{v_1^2 + v_2^2 + \dots + v_n^2}

语法

Math.hypot([value1[,value2, ...]]) 

参数

value1, value2, ...
任意多个数字

描述

由于 hypotMath 的静态方法,所以应该像这样使用:Math.hypot(),而不是作为你创建的 Math 实例的属性(Math 不是一个构造函数)。

如果不传入任何参数, 则返回 +0 .

如果参数列表中有至少一个参数不能被转换为数字,则返回 NaN.

如果只传入一个参数, 则 Math.hypot(x) 的效果等同于 Math.abs(x).

示例

Math.hypot(3, 4)        // 5
Math.hypot(3, 4, 5)     // 7.0710678118654755
Math.hypot()            // 0
Math.hypot(NaN)         // NaN
Math.hypot(3, 4, "foo") // NaN, +"foo" => NaN
Math.hypot(3, 4, "5")   // 7.0710678118654755, +"5" => 5
Math.hypot(-3)          // 3, the same as Math.abs(-3)

Polyfill

此函数可以使用如下代码模拟:

if (!Math.hypot) {
  Math.hypot = function hypot() {
    var y = 0;
    var length = arguments.length;

    for (var i = 0; i < length; i++) {
      if(arguments[i] === Infinity || arguments[i] === -Infinity) {
        return Infinity;
      }
      y += arguments[i] * arguments[i];
    }
    return Math.sqrt(y);
  };
}

规范

规范链接 规范状态 备注
ECMAScript 2015 (6th Edition, ECMA-262)
Math.hypot
Standard  

浏览器兼容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 38 27 (27) 未实现 25 7.1
Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support 未实现 27.0 (27) 未实现 未实现 未实现

相关链接