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() 方法计算无穷大,结果仍然介于 -π 和 π − 之间。
<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 作为结果。

