开发者社区 问答 正文

js  递归?通俗的描述递归,下面这个例子如何理解

function rec(x){
if(x!==1){
   console.log(x)
    rec(x-1)
   console.log(x) 
   }   
}
rec(5) //输出为5 4 3 2 2 3 4 5

展开
收起
a123456678 2016-03-11 13:41:15 1787 分享 版权
1 条回答
写回答
取消 提交回答
  • function rec(x){
        if(x!==1){
            console.log("test1:", x); 
            rec(x-1); 
            console.log("test2", x);
         } else {
             console.log("test", x);
         }
    }
    rec(5);

    题主执行下这段代码,就能看到执行顺序了,当x>1时,满足if的判断,打印test1,然后递归调用rec(x-1),进入下一次循环,这里不会打印test2,直到x=1,打印test。然后开始执行rec(x-1)后面的部分的代码。
    题主不嫌麻烦可以看如下的代码,基本上递归就是用一种优雅的方式做了下面代码做的事情。

    function rec(x){
        if(x!==1){
            console.log("test1:", x); 
            //我把调用自身函数直接写进来
            var a = x - 1;
            if(a!==1){
                console.log("test1:", a);
                //我把调用自身函数直接写进来 
                var b = a - 1;
                if(b!==1) {
                  ...
                  ...
                  ...
                }
                console.log("test2", a)
            }
            console.log("test2", x);
         } else {
             console.log("test", x);
         }
    }
    rec(5);
    2019-07-17 18:59:04
    赞同 展开评论
问答分类:
问答地址: