簡體   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