JavaScript Math.atan2() 方法



JavaScript 中的Math.atan2() 方法用於計算其引數商的反正切值,表示以弧度為單位的角度。它接受兩個引數 y 和 x,並計算正 x 軸和點 (x, y) 之間的角度。結果將在 -π 到 π 範圍內,或 -180 度到 180 度。

語法

以下是 JavaScript Math.atan2() 方法的語法:

Math.atan2(y, x)

引數

此方法僅接受兩個引數。下面描述了這些引數:

  • y: 垂直座標。
  • x: 水平座標。

返回值

此方法返回一個數值,表示正 x 軸和點 (x, y) 之間的角度(以弧度為單位,介於 -π 和 π 之間,包括 -π 和 π)。

示例 1

在下面的示例中,我們使用 JavaScript Math.atan2() 方法計算 (1/1) 的反正切值:

<html>
<body>
<script>
   const result = Math.atan2(4, 1);
   document.write(result);
</script>
</body>
</html>

輸出

如果我們執行上述程式,它將返回大約“0.7853”(45 度的弧度值)。

示例 2

在此示例中,由於 y 引數為 0,因此結果角度將為 0:

<html>
<body>
<script>
   const result = Math.atan2(0, 1);
   document.write(result);
</script>
</body>
</html>

輸出

正如我們在輸出中看到的,它返回 0 作為結果。

示例 3

如果我們使用 atan2() 方法與 Infinity,結果仍然在 -π 和 π 之間:

<html>
<body>
<script>
   const result1 = Math.atan2(Infinity, 0);
   const result2 = Math.atan2(-Infinity, 0);
   const result3 = Math.atan2(Infinity, -Infinity);
   document.write(result1, "<br>", result2, <br>", result3);
</script>
</body>
</html>

輸出

正如我們在輸出中看到的,結果在 -π 和 π 之間。

示例 4

如果我們向 atan2() 方法傳遞字串引數,結果將為“NaN”:

<html>
<body>
<script>
   const result = Math.atan2("Tutorialspoint", "Tutorix");
   document.write(result);
</script>
</body>
</html>

輸出

正如我們在輸出中看到的,它返回 NaN 作為結果。

廣告