JavaScript Math.log10() 方法



JavaScript 中的Math.log10() 方法接受一個數字作為引數(應大於 0),並返回該數字以 10 為底的對數。

需要注意的是,傳遞給 Math.log10() 的引數必須是正數。如果傳遞非正數,Math.log10() 將返回 NaN(非數字)。此外,如果將 NaN 或 Infinity 作為引數傳遞給此方法,它將返回相同的值。

語法

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

Math.log10(x)

引數

此方法只接受一個引數。如下所述:

  • x: 一個數值。

返回值

此方法返回給定數字以 10 為底的對數(以 10 為底的對數)。

示例 1

在下面的示例中,我們使用 JavaScript 中的 Math.log10() 方法計算 5 的以 10 為底的對數:

<html>
<body>
<script>
   const result = Math.log10(5);
   document.write(result);
</script>
</body>
</html>

輸出

執行上述程式後,它將返回大約 0.6989 的結果。

示例 2

在這裡,我們獲取 1 的以 10 為底的對數:

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

輸出

它返回 0 作為結果。

示例 3

如果我們為該方法提供 0 或 -0 作為引數,它將返回 -Infinity 作為結果:

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

輸出

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

示例 4

如果我們提供的引數小於 0,此方法將返回 NaN(非數字):

<html>
<body>
<script>
   const result = Math.log10(-5);
   document.write(result);
</script>
</body>
</html>

輸出

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

廣告