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
递归有个退出条件,就是x == 1
不满足退出条件,就调用自己,传入新的参数x-1,
具体过程你可以在chrome中打断点
两个console因为是在递归调用前后,所以会打印出来对称的
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);