JavaScript Math.log() 方法



在 JavaScript 中,Math.log() 方法用於計算一個數的自然對數(以 e 為底)。一個數 x 的自然對數,記為 ln(x),是指將數學常數 e(大約等於 2.71828)提升到哪個指數才能得到 x 的值。

如果提供的引數是正數或負數 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,則此方法返回 -Infinity 作為結果:

<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 作為結果。

廣告