求幂 (**)

求幂运算符(**)返回将第一个操作数加到第二个操作数的幂的结果。它等效于Math.pow,不同之处在于它也接受BigInts作为操作数。

语法

Operator: var1 ** var2

简介

求幂运算符是是右结合的a ** b ** c 等于 a ** (b ** c).

在大多数语言里,比如PHP、Python等那些有一个幂运算符 (**) 的语言,幂运算符被定义有一个比一元运算符,比如一元的 + 和一元的 - 更高的运算顺序,但有一些例外。在Bash语言里,** 运算符被定义有一个比一元运算符更低的运算顺序。

在JavaScript里,你不可能写出一个不明确的求幂表达式。这就是说,你不能立刻将一个一元运算符(+/-/~/!/delete/void/typeof)放在基数前,这样做只会导致一个语法错误。

-2 ** 2; 
// 4 in Bash, -4 in other languages. 
// This is invalid in JavaScript, as the operation is ambiguous. 


-(2 ** 2); 
// -4 in JavaScript and the author's intention is unambiguous. 

注意有些编程语言用扬抑符 ^ 做乘方运算,但是JavaScript将这个符号作为了XOR位逻辑运算符

例子

基本求幂

2 ** 3   // 8
3 ** 2   // 9
3 ** 2.5 // 15.588457268119896
10 ** -1 // 0.1
NaN ** 2 // NaN

结合

2 ** 3 ** 2   // 512
2 ** (3 ** 2) // 512
(2 ** 3) ** 2 // 64

与一元运算符的用法

取求幂表达式的值的相反数:

-(2 ** 2) // -4

将求幂表达式的底数转化为一个负数:

(-2) ** 2 // 4

规范

Specification
ECMAScript (ECMA-262)
Exponentiation operator

浏览器支持

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
Exponentiation (**)Chrome Full support 52Edge Full support 14Firefox Full support 52IE No support NoOpera Full support 39Safari Full support 10.1WebView Android Full support 51Chrome Android Full support 52Firefox Android Full support 52Opera Android Full support 41Safari iOS Full support 10.3Samsung Internet Android Full support 6.0nodejs Full support 7.0.0
Full support 7.0.0
Full support 6.5.0
Disabled
Disabled From version 6.5.0: this feature is behind the --harmony runtime flag.

Legend

Full support  
Full support
No support  
No support
User must explicitly enable this feature.
User must explicitly enable this feature.

See also