Math.tan()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Math.tan() 靜態方法返回一個數字(以弧度為單位)的正切值。

試一試

function getTanFromDegrees(degrees) {
  return Math.tan((degrees * Math.PI) / 180);
}

console.log(getTanFromDegrees(0));
// Expected output: 0

console.log(getTanFromDegrees(45));
// Expected output: 0.9999999999999999

console.log(getTanFromDegrees(90));
// Expected output: 16331239353195370

語法

js
Math.tan(x)

引數

x

一個代表以弧度為單位的角度的數字。

返回值

x 的正切值。如果 xInfinity-InfinityNaN,則返回 NaN

注意: 由於浮點數的精度問題,無法獲得 π/2 的精確值,因此在結果不是 NaN 的情況下,其值始終是有限的。

描述

由於 tan()Math 的靜態方法,您始終透過 Math.tan() 來呼叫它,而不是透過您建立的 Math 物件的方法(Math 不是建構函式)。

示例

使用 Math.tan()

js
Math.tan(-Infinity); // NaN
Math.tan(-0); // -0
Math.tan(0); // 0
Math.tan(1); // 1.5574077246549023
Math.tan(Math.PI / 4); // 0.9999999999999999 (Floating point error)
Math.tan(Infinity); // NaN

Math.tan() 和 π/2

無法精確計算 tan(π/2)

js
Math.tan(Math.PI / 2); // 16331239353195370
Math.tan(Math.PI / 2 + Number.EPSILON); // -6218431163823738

使用 Math.tan() 處理角度值

由於 Math.tan() 函式接受弧度值,但通常使用角度值會更方便,因此下面的函式接受一個角度值,將其轉換為弧度,然後返回其正切值。

js
function getTanDeg(deg) {
  const rad = (deg * Math.PI) / 180;
  return Math.tan(rad);
}

規範

規範
ECMAScript® 2026 語言規範
# sec-math.tan

瀏覽器相容性

另見