使用带有 while 循环的递归的奇怪结果 [英] Strange result using recursion with while loop

查看:42
本文介绍了使用带有 while 循环的递归的奇怪结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Javascript 的初学者.当我自己尝试递归时,我使用 while 循环得到了一些奇怪的结果.使用 If 语句得到正确的结果.

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.

这是代码和结果:

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

test(5);

结果:

5432112113211211432112113211211

5432112113211211432112113211211

使用If语句时

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

test(5);

结果是:

54321

我无法在 while 情况下真正调试它.老实说,这让我在某些时候感到困惑.

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

推荐答案

需要注意的重要一点是,每次在 f 中运行代码时,都会创建一个带有 new 变量称为 n.因此,通过递归调用 f,您将添加到作用域链中.您不断添加到作用域链,直到 n >0false.一旦它为假,您就开始向上遍历作用域链,其中存在 nother 版本.重复该过程,直到所有范围内的所有 n 变量都变为 0.

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

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

这里有一个 jsfiddle 应该会有帮助. 它打印两个数字:第一个代表哪个您所在的范围,第二个与您在代码中打印的数字相同.查看第一个数字,并尝试了解如何为每个范围创建一个新数字.当您稍后在程序中返回该范围时,请尝试考虑 n 的值应该是什么.

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.

这篇关于使用带有 while 循环的递归的奇怪结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆