此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Math.tanh()

基线 广泛可用

自 2015年7月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

Math.tanh() 函数将会返回一个数的双曲正切函数值,公式如下:

tanhx=sinhxcoshx=ex-e-xex+e-x=e2x-1e2x+1\tanh x = \frac{\sinh x}{\cosh x} = \frac {e^x - e^{-x}} {e^x + e^{-x}} = \frac{e^{2x} - 1}{e^{2x}+1}

尝试一下

console.log(Math.tanh(-1));
// Expected output: -0.7615941559557649

console.log(Math.tanh(0));
// Expected output: 0

console.log(Math.tanh(Infinity));
// Expected output: 1

console.log(Math.tanh(1));
// Expected output: 0.7615941559557649

语法

Math.tanh(x)

参数

x

待计算的数字。

返回值

所给数字的双曲正切值。

描述

因为 tanh()Math 的静态方法,所以总应该直接调用 Math.tanh() ,而不是创建 Math 对象再调用该方法(Math 不是一个构造函数)。

示例

使用 Math.tanh()

js
Math.tanh(0); // 0
Math.tanh(Infinity); // 1
Math.tanh(1); // 0.7615941559557649

向下兼容

tanh() 可以通过 Math.exp() 函数实现:

js
Math.tanh =
  Math.tanh ||
  function (x) {
    var a = Math.exp(+x),
      b = Math.exp(-x);
    return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (a + b);
  };

规范

规范
ECMAScript® 2027 Language Specification
# sec-math.tanh

浏览器兼容性

参见