JavaScript Math.log() 方法
在 JavaScript 中,Math.log() 方法用于计算数字的自然对数(底数为 e)。数字 x 的自然对数,表示为 ln(x),是数学常数 e(约等于 2.71828)的指数,必须以此指数为底才能得到 x 的值。
如果提供的参数为正 0 或负 0,则此方法返回"-Infinity"。如果参数小于 0,则返回 NaN(非数字)。
语法
以下是 JavaScript Math.log() 方法的语法 -
Math.log(x)
参数
此方法仅接受一个参数。下文同样描述 -
- x: 一个数值。
返回值
此方法返回所提供数值表达式的自然对数(底数为 e)。
示例 1
在下面的示例中,我们使用 JavaScript Math.log() 方法计算 10 的自然对数 -
<html> <body> <script> const result = Math.log(10); document.write(result); </script> </body> </html>
输出
执行上述程序后,返回约 2.3025。
示例 2
这里,我们计算 1 的自然对数 −
<html> <body> <script> const result = Math.log(1); document.write(result); </script> </body> </html>
输出
1 的自然对数为 0,因为 e^0 等于 1。
示例 3
如果提供的参数为 0 或 -0,则此方法返回负无穷大作为结果 -
<html> <body> <script> const result1 = Math.log(0); const result2 = Math.log(-0); document.write(result1, <br>, result2); </script> </body> </html>
输出
如果执行该程序,它将返回 -Infinity。
示例 4
如果给定的参数小于 0,此方法将返回 NaN 作为结果 -
<html> <body> <script> const result = Math.log(-1); document.write(result); </script> </body> </html>
输出
这里,-1 小于 0,因此返回 NaN 作为结果。

