【问题标题】:Explain this JavaScript Recursion解释这个 JavaScript 递归
【发布时间】:2021-11-04 00:41:24
【问题描述】:

解释一下这个 JavaScript 递归,当 0 function-foo 返回 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 }

【问题讨论】:

    标签: javascript arrays recursion


    【解决方案1】:

    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]
    

    【讨论】:

    • 在某些时候 iBoolean(0<0) evals 到 false 那么 foo(3) 什么时候 eval 到 true 到返回?不仅负数会使其成为真的,即Boolean(-1&lt;0) evals to true
    • 添加了Boolean(i&lt;0) 以检查 i
    • @Jay ,当 i = -1 , (i
    猜你喜欢
    • 1970-01-01
    • 2016-10-04
    • 2018-02-26
    • 1970-01-01
    • 2022-07-04
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多