JavaScript 中的指數
Harshit Jindal
2023年10月12日
JavaScript
JavaScript Math
本教程講解如何在 JavaScript 中獲取數字的指數。JavaScript 為我們提供了兩種方法來實現這一目標。我們可以使用 Math.pow() 函式或指數運算子**。
JavaScript 中使用 Math.pow() 來計算指數
Math.pow() 函式用於計算數字的冪,即,將 base 轉換為 exponent(baseexponent)的冪。如果 base 為負且 exponent 不是整數,則返回 NaN。它是一個靜態函式,始終用作 Math.pow(),而不用作 Math 類的物件。
Math.pow() 的語法
Math.pow(base, exponent)
Math.pow() 引數
base:底數。exponent:指數。
Math.pow() 的返回值
Math.pow() 方法返回(baseexponent)。
使用 Math.pow() 的示例
console.log(Math.pow(7, 2));
console.log(Math.pow(4, 0.5)));
console.log(Math.pow(7, -2));
console.log(Math.pow(-7, 2));
console.log(Math.pow(-7, 1 / 3));
輸出:
49
2
0.020408163265306124
49
NaN
所有主要的瀏覽器都支援此方法。
JavaScript 中的冪運算子**
冪運算子(**)返回將 base 的 exponent 次冪的結果,即(baseexponent)。它是一個右關聯運算子,因此 a ** b ** c 與 a ** (b ** c) 相同。
例子
2 ** 3 // 8
NaN ** 2 // NaN
3 ** 2.5 // 15.588457268119896
10 ** -1 // 0.1
它的優點是它也支援大整數,但是同時,它的缺點是我們必須在括號中保留負數底數。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Harshit Jindal
Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.
LinkedIn