Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

javascript - 解释递归函数中变量的作用域(Explaining the scoping of variables in recursive functions)

I am trying to explain to a student I am helping out at school with an ICT exam question on Javascript how the function below is returning 24. I am an economics teacher by training who dabbles in programming.(我试图向学生解释我正在学校中通过Javascript进行ICT考试的问题,以帮助下面的函数恢复正常。24.我是一名经济老师,受过培训,涉猎编程。)

I know it is a simple example of recursion but I am not sure of the actual step by step process and the scoping of the variable N. Is anyone able to explain step by step and clearly how this is working.(我知道这是一个简单的递归示例,但是我不确定实际的逐步过程和变量N的作用域。是否有人能够逐步解释并清楚其工作原理。)
function mystery(n){
 if(n==0)
 return 1;
 return  n* mystery(n-1);
}

console.log(mystery(4));
  ask by jon translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Step by step(一步步)

 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 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...