nodejs 递归问题
发布于 11 年前 作者 leeson 11063 次浏览 最后一次编辑是 8 年前

result = [ { cid: 59, pid: 0, name: ‘PHP’ }, { cid: 19, pid: 0, name: ‘C++’ }, { cid: 20, pid: 19, name: ‘STL’ }, { cid: 21, pid: 19, name: ‘MFC’ }, { cid: 60, pid: 59, name: ‘Zend Framework’ } ];

function test(result, pid) { rtn = []; for(i in result) { if(result[i].pid == pid) { result[i].children = test(result, result[i].cid); rtn.push(result[i]); } } return rtn; }

tree = test(result, 0); console.log(tree); // 结果却是下边这样 [ { cid: 60, pid: 59, name: ‘Zend Framework’, children: [ [Circular], [Circular] ] }, { cid: 60, pid: 59, name: ‘Zend Framework’, children: [ [Circular], [Circular] ] } ]

由test递归调用将result元数据组成树状,可是结果却不正确,请教!!!,还有,其中children里的值是“Circular”是什么意思?

5 回复

[Circular] simply means circular reference.

var o = {
    "self": o
}

Is shown as

{
    "self": [Circular]
}

It could be shown as

{
    "self": {
         "self": {
              "self": {
                   ...
              }
         }
    }
}

兄弟呀,你坑死我了,我被你的代码带到坑里了。

你为什么声明变量的时候不带var那?不带var的话,就会变成全局变量,就会导致数据在迭代之后,就乱掉了。

总共3个地方没有带var,带上就完全正确了。

因为你的代码逻辑非常棒,代码量非常少,让我整整看了2个小时,最后发现竟然是变量的错误引起的,郁闷呀。

@yusk013哈哈,不好意思。谢谢你,按你的方法完全正确

哈哈,好欢乐

回到顶部