【发布时间】:2019-06-02 18:05:19
【问题描述】:
这是代码。
var temp = [
{
slugs: ['men'],
children: [
{ slugs: ['men', 'tops'], children: [
{ slugs: ['men', 'tops', 'shirts'] },
{ slugs: ['men', 'tops', 'swe'] }
] },
{
slugs: ['men', 'bottoms'], children: [
{ slugs: ['men', 'bottoms', 'pants'] },
{ slugs: ['men', 'bottoms', 'under'] }
]
}
]
},
{
slugs: ['women'],
children: [
{ slugs: ['women', 'tops'], children: [
{ slugs: ['women', 'tops', 'shirts'] },
{ slugs: ['women', 'tops', 'swe'] }
] },
{
slugs: ['women', 'bottoms'], children: [
{ slugs: ['women', 'bottoms', 'pants'] },
{ slugs: ['women', 'bottoms', 'under'] }
]
}
]
}
]
function matchTreeObj (tree, location) {
if (_.isArray(tree) && tree.length > 0) {
for(let i=0;i<tree.length;i++){
matchTreeObj(tree[i], location)
}
}
if (tree.slugs && (tree.slugs.join('/') === location)) {
console.log(tree)
return tree
} else if (tree.children && tree.children.length > 0) {
matchTreeObj(tree.children, location)
}
}
const aaa = matchTreeObj(temp, 'men/tops')
console.log('from log', aaa)
它正在使用 lodash,fiddle 在这里。
该代码基本上输出其slugs 值与位置参数匹配的对象块。
我可以让控制台日志正常工作。但我无法获得返回的数据。 (我已经尝试返回递归使用它的函数,但仍然无法正常工作。)
我做错了什么?
【问题讨论】:
标签: javascript algorithm for-loop recursion search