【问题标题】:While loop inside recursive function failed if looped more than once如果循环不止一次,则递归函数内的循环失败
【发布时间】:2021-02-21 12:03:32
【问题描述】:

如果 while 循环条件为

var data = {
    a: "abc",
    c: 0
}

function recurse(data, nodes) {
    const first = nodes.shift();
    console.log("first-"+first.id, first.t);

    if (first.t == "action") {
        data.c = data.c + 1;
        console.log("exec action", data.c);
    } else {
        switch (first.t) {
            case "if_else":
                console.log(recurse(data, first.b[0].actions), 300);
                break
            case "while":
                var brNodes = first.b[0].actions
                while (data.c < 7) {
                  console.log(recurse(data, brNodes), 400);
                }
                break
            default:
                break
        }
    }
    
    return (nodes.length > 0)? console.log(recurse(data, nodes), 200): "Completed"
} 

var actions = [
    {id:1, t:"action", b:null},
    {id:2, t:"action", b:null},
    {id:3, t:"if_else", b:[{id:31, t:"branch", actions:[{id:311, t:"action", b:null}, {id:312, t:"action", b:null}]},{id:32, t:"branch", actions:[{id:321, t:"action", b:null}]}]},
    {id:4, t:"action", b: null},
    {id:5, t:"while", b:[{id:500, t:"branch", actions:[{id:511, t:"action", b:null}]}]},
    {id:6, t:"action", b:null}
]

console.log(recurse(data, actions), 100) 

这是我在 StackBlitz 上的测试https://stackblitz.com/edit/recurse?file=index.js

【问题讨论】:

  • 我在您的actions 中没有看到任何data.c 字段
  • @ManuelSpigolon - datadata.c 在 OP 代码块的开头定义。
  • 预期输出是什么?

标签: node.js loops recursion while-loop


【解决方案1】:

看起来我自己已经弄清楚了...该数组是通过引用传入的,在第一个循环之后它被消耗到一个空数组中。我用 [...] spread 替换了它

console.log(recurse(data, [...first.b[0].actions]), 400);

这应该解决

【讨论】:

    【解决方案2】:

    您的代码正在这样做:

    const first = nodes.shift();
    

    然后,尝试访问:

     first.b[0].actions
    

    并且,nodes.shift()nodes 数组中删除第一个元素。您的节点数组有 6 个项目。如果您尝试通过将条件设置为 while (data.c &lt; 7) 来调用您的函数 7 次,您将得到一个空的 nodes 数组,因此在最后一次迭代中 first 中的 undefined 值将导致错误当您的代码在最后一次迭代中尝试访问 first.b[0].actions 时。

    【讨论】:

    • @kkgan - 这回答了你的问题吗?如果是这样,您可以通过单击答案左侧的复选标记向社区表明这一点,这也将为您在此处获得一些声誉积分,以遵循正确的程序。
    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2021-10-21
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2016-03-18
    相关资源
    最近更新 更多