Math.tanh()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

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);
  };

规范

Specification
ECMAScript® 2025 Language Specification
# sec-math.tanh

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
tanh

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见