You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求拆解《Eloquent JavaScript》中幂函数返回1024的执行逻辑

拆解幂函数 power(2,10) 的执行全过程

先明确原函数的代码(来自《Eloquent JavaScript》第三章):

const power = function(base, exponent) {
  let result = 1;
  for (let count = 0; count < exponent; count++) {
    result *= base;
  }
  return result;
};

核心逻辑概述

这个函数通过循环累乘实现幂运算:初始化结果变量为1,重复exponent次将结果与底数相乘,最终得到底数的exponent次幂。

调用 power(2,10) 的逐步骤拆解

调用时,base参数为2,exponent参数为10,具体执行流程如下:

  1. 初始化阶段

    • 声明result变量并赋值为1
    • 进入for循环,初始化循环变量count为0
  2. 循环迭代(共执行10次)
    循环条件是count < 10,每次迭代后count自增1,直到count等于10时退出循环:

    • 第1次循环:count=0,满足0<10 → result = 1 * 2 = 2,count变为1
    • 第2次循环:count=1,满足1<10 → result = 2 * 2 = 4,count变为2
    • 第3次循环:count=2,满足2<10 → result = 4 * 2 = 8,count变为3
    • 第4次循环:count=3,满足3<10 → result = 8 * 2 = 16,count变为4
    • 第5次循环:count=4,满足4<10 → result = 16 * 2 = 32,count变为5
    • 第6次循环:count=5,满足5<10 → result = 32 * 2 = 64,count变为6
    • 第7次循环:count=6,满足6<10 → result = 64 * 2 = 128,count变为7
    • 第8次循环:count=7,满足7<10 → result = 128 * 2 = 256,count变为8
    • 第9次循环:count=8,满足8<10 → result = 256 * 2 = 512,count变为9
    • 第10次循环:count=9,满足9<10 → result = 512 * 2 = 1024,count变为10
  3. 循环退出与返回结果
    当count=10时,10 < 10不成立,循环结束。函数返回result的值1024,这就是2^10的计算结果。

内容的提问来源于stack exchange,提问作者Agacia Cloud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 20:45:06