首页 > 解决方案 > 解释这个 JavaScript 递归

问题描述

解释一下这个 JavaScript 递归,当 0<0 表达式对 foo(3) 进行 eval 时究竟会发生什么?
function-foo return console.log("test")
是不是在return语句中传递的console.log()异常?
是否该数组对于索引 3 和 4 有两个 0,因为 foo 评估 0 两次,因为一旦 i-1 达到 1-1 递归调用应该是 foo(0) 是的?
但是继续,但是 console.log 被调用了两次,其中 foo() 递归调用在两者之间被提升了 order 在这里有什么区别?
我不明白为什么这些是结果

let ar = [];

function foo(i) {
  if (i < 0)
    return console.log("test");

  ar.push(i);
  console.log(i, Boolean(i<0));
  foo(i - 1);
  ar.push(i);
  console.log(i, Boolean(i<0));
}

foo(3)
console.log('ar=', JSON.stringify( ar )) 
.as-console-wrapper { max-height: 100% !important; top: 0 }

标签: javascriptarraysrecursion

解决方案


你做的递归代码foo(3)

function foo(i) {
  if (i < 0) return   // stop recursive call
  ar.push(i)          // first push
  foo(i - 1)          // recursive call
  ar.push(i)          // second push
}
ar.push(3)                // ar = [3]         ==== firsts push
    ar.push(2)            // ar = [3,2]
        ar.push(1)        // ar = [3,2,1]
            ar.push(0)    // ar = [3,2,1,0]
                return    // i == -1 , (i<0) is true => no pushS, no foo(i - 1)
            ar.push(0)    // ar = [3,2,1,0,0]  === seconds push
        ar.push(1)        // ar = [3,2,1,0,0,1]
    ar.push(2)            // ar = [3,2,1,0,0,1,2]
ar.push(3)                // ar = [3,2,1,0,0,1,2,3]

推荐阅读