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