繁体   English   中英

解释递归函数中变量的作用域

[英]Explaining the scoping of variables in recursive functions

我试图向一个学生解释我在学校帮助解决关于 Javascript 的 ICT 考试问题,下面的函数如何返回 24。我是一名经济学老师,通过培训涉足编程。 我知道这是递归的一个简单示例,但我不确定实际的逐步过程和变量 N 的范围。是否有人能够逐步解释清楚这是如何工作的。

function mystery(n){
 if(n==0)
 return 1;
 return  n* mystery(n-1);
}

console.log(mystery(4));

一步步

 function mystery(n){ console.log('n=',n); // I add this to see 'call stack' if(n==0) return 1; return n * mystery(n-1); } console.log(mystery(4)); // Execution looks like this // // 1. console.log(mystery(4)); // 2. run for n=4 // function mystery(4){ // if(4==0) return 1; // return 4 * mystery(4-1); // we call here mystery(3) // } // 3. The mystery(3) is // function mystery(3){ // if(3==0) return 1; // return 3 * mystery(3-1); // we call here mystery(2) // } // 4. The mystery(2) is // function mystery(2){ // if(2==0) return 1; // return 2 * mystery(2-1); // we call here mystery(1) // } // 5. The mystery(1) is // function mystery(1){ // if(1==0) return 1; // return 1 * mystery(1-1); // we call here mystery(0) // } // 6. The mystery(0) is // function mystery(0){ // if(0==0) return 1; // we return 1 here // return 0 * mystery(0-1); // } // // So at the end the mystery(4) returns: // return 4 * 3 * 2 *1 * 1

如果您通过一些日志记录来增强功能,则很容易将递归深度及其在每次调用中下降和上升的方式可视化:

function log(indentation) {
  var args = ['  '.repeat(indentation)]
    .concat(Array.from(arguments).slice(1));
  console.log.apply(null, args);
}

function mystery(n, depth) {
  if (n === 0) {
    log(depth, 'mystery called with n =', n, 'returning 1');
    return 1;
  } else {
    log(
      depth, 'mystery called with n =', n,
     'going into recursion: multiplying with mystery(', n - 1, ')'
    );
    var result = n * mystery(n - 1, depth + 1);
    log(
      depth, 'mystery called with n =', n,
      'returning', result, ' after recursion'
    );
    return result;
  }
}

var initialDepth = 0;
mystery(4, initialDepth);


// Output:

mystery called with n = 4 going into recursion: multiplying with mystery( 3 )
  mystery called with n = 3 going into recursion: multiplying with mystery( 2 )
    mystery called with n = 2 going into recursion: multiplying with mystery( 1 )
      mystery called with n = 1 going into recursion: multiplying with mystery( 0 )
        mystery called with n = 0 returning 1
      mystery called with n = 1 returning 1  after recursion
    mystery called with n = 2 returning 2  after recursion
  mystery called with n = 3 returning 6  after recursion
mystery called with n = 4 returning 24  after recursion

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM