← 中文资源

简体中文版本

幂运算右结合并溢出为 Infinity

** 与 Math.pow 等价但右结合:2 ** 3 ** 2 是 512 不是 64;支持负指数与小数指数,结果超出 double 范围直接溢出为 Infinity,**= 提供原地更新。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

2 ** 10: 1024
Math.pow: 1024
2 ** 3 ** 2: 512
(2 ** 3) ** 2: 64
2 ** -2: 0.25
9 ** 0.5: 3
1e200 ** 2: Infinity
depth: 8

实现说明

顶层就这几处状态:depth。

使用要点

  • 每一步打印都带着自己的标签:2 ** 10:、Math.pow:、2 ** 3 ** 2:。

常见问题

运行前要先安装什么?

什么都不用额外装——运行时自带了代码所需的一切。 文件用顶层绑定保存自己的状态:depth。

核心语句

let depth = 2;
depth **= 3;

代码示例

// ** is equivalent to Math.pow
console.log('2 ** 10:', 2 ** 10);
console.log('Math.pow:', Math.pow(2, 10));

// right-associative: the right-hand exponent is evaluated first
console.log('2 ** 3 ** 2:', 2 ** 3 ** 2);
console.log('(2 ** 3) ** 2:', (2 ** 3) ** 2);

// negative and fractional exponents are both supported
console.log('2 ** -2:', 2 ** -2);
console.log('9 ** 0.5:', 9 ** 0.5);

// a result beyond the double range becomes Infinity
console.log('1e200 ** 2:', 1e200 ** 2);

// **= updates in place
let depth = 2;
depth **= 3;
console.log('depth:', depth);