gpt4 book ai didi

Javascript递归函数似乎在第一次通过后退出

转载 作者:行者123 更新时间:2023-11-30 23:41:51 25 4
gpt4 key购买 nike

我试图在通过设置节点(索引)进行递归时呈现树状层次结构。我已经知道根源(顶部)。有多个根元素。我试图收集变量 tree 中的整个 html(这整个 html 稍后将附加到 div 中)

tree = "";
top = ["1", "11", "14", "17", "72", "73", "74", "78", "79", "98", "99"];
index = {
1: {
'name': "Node 1",
'children': "2,3,4,5,6,7,8,9,10"
},
2: {
'name': "Node 2",
'children': ""
},

//.... goes all the way upto 99
}

递归函数 makeFT(index,roots) 似乎仅在遍历“顶部”数组中第一个元素的子元素后才会中断。

此代码位于 jsbin及以下。可能是什么问题呢?有一个更好的方法吗?如有任何帮助,我们将不胜感激。

makeFT(index, top);


function makeFT(index, roots) {
console.log(roots);
tree == "" ? tree += '<ul>' : tree += '<ul><hr/>'
for (i = 0; i < roots.length; ++i) {
n = parseInt(roots[i]);
//console.log(n);
//console.log(index[n]);

tree += '<li>' + roots[i] + '</span>' + index[n].name;

if (index[n].children === "") {
tree += '<input class="leaf tree-first-input" type="text" size="2">'
}
else {
tree += '<input class="non-leaf tree-first-input" type="text" size="2">'
makeFT(index, index[n].children.split(","));
}
tree += "</li>"
}
tree += '</ul><br/>'

}

更新:事实证明这是一个范围问题而不是递归问题。递归没问题。由于我在循环 root 数组时没有定义变量“i”的范围,因此每个后续递归函数都继承了无范围“i”的值,从而产生了问题。

最佳答案

在函数内添加 var i=0。您对 i 存在范围界定问题。

http://jsbin.com/ugoju4/12/edit

关于Javascript递归函数似乎在第一次通过后退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4345373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com