我的菜单将“选定”数组呈现为选项。然后,当选择一个项目时,它会将其分支呈现为新选项。
为了跟踪遍历,我创建了一个名为 select 的数组。因此,如果有人选择第 3 个选项,然后选择第 1 个选项,然后选择第 6 个选项,select = [3,1,6]
只需将索引插入数组就足够简单了,我的问题是如何使用这个数组创建对树的引用?
如果 select 是 [3,1,6] 我想创建一个函数来引用 tree[3][1][6]
也允许我通过剪裁向后遍历数组的最后一个值。
(在 CoffeeScript 中)
tree:
name: 'name1'
branches:[
name: 'name2'
branches: [
name: 'name3'
branches: [
name: 'name4'
branches:[]
,
name: 'name5'
branches:[]
,
name: 'name6'
branches:[]
]
]
]
current = tree
#when clicked
$('.menu li').on 'click', ()->
select.push($(this).index())
for value in select
current = current+'['+value+']'
#this results in a string, not an actual reference to the tree.
最佳答案
如果我正确理解您的需求,将最后两行更改为以下内容应该可以解决问题:
current = tree
for value in select
current = current['branches'][value]
关于javascript - 遍历数组树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8486919/