Strange result using recursion with while loop

喜你入骨 提交于 2020-01-15 05:09:07

问题


I'm a beginner in Javascript. And while trying recursion by myself, i got some strange result using while loop. And just the right result using If statement.

Here's the code and the result :

var test = function f(n){
    while(n > 0){
        document.write(n);
        f(--n);     
    }
};

test(5);

And the result :

5432112113211211432112113211211

While using If statement

var test = function f(n){
    if(n > 0){
        document.write(n);
        f(--n);     
    }
};

test(5);

The result is :

54321

I can't really debug it in the while case. It gets me confused at some point to be honest.


回答1:


The important thing to note is that every time you run the code inside of f, a new scope is created with a new variable called n. So, by recursively calling f, you are adding to scope chain. You keep adding to the scope chain until n > 0 is false. Once it is false, you start traversing back up the scope chain, where other versions of n exist. The process repeats until all n variables in all of the scopes become 0.

Notice the pattern that occurs when I add some spaces to your numbers below. I've added a space every time the code has to go up the scope chain. Every set of numbers represents the code going down the scope chain.

54321 1 21 1 321 1 21 1 4321 1 21 1 321 1 21 1

Here is a jsfiddle that should be helpful. It prints two numbers: the first one represents which scope you are in and the second one is the same number that you were printing in your code. Look at the first numbers and try to wrap your head around how a new number is created for each scope. Try to think about what the value of n should be when you return to that scope later in the program.




回答2:


5432112113211211432112113211211 You can see the pattern:

5432112113211211
 432112113211211

543211211
  3211211
 43211211
  3211211

543211
   211
  3211
   211
 43211
   211
  3211
   211

etc

These are just all the loops it goes through. First it prints 5, then splits of for 4 and splits again for 3 etc.



来源:https://stackoverflow.com/questions/11423420/strange-result-using-recursion-with-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!