求幂运算符(**
)返回将第一个操作数加到第二个操作数的幂的结果。它等效于Math.pow
,不同之处在于它也接受BigInts
作为操作数。
demo
console.log(3 ** 4);
// expected output: 81
console.log(10 ** -2);
// expected output: 0.01
console.log(2 ** 3 ** 2);
// expected output: 512
console.log((2 ** 3) ** 2);
// expected output: 64
简介
求幂运算符是是右结合的: 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.
基本求幂
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 需要注意的括号的优先级