我正在处理一组类别对象,这些类别对象可以有一组子类别对象。棘手的部分是这个嵌套数据的深度是未知的(并且可以改变)。 (请参阅底部的示例。)我想做的是将“踪迹”返回到类别对象,但我遇到了各种困难。
理想情况下像
findCategory('b4')
这样的东西会返回:['c1', 'd2', 'd3', 'b4']
(见示例)。
我认为我的问题是我无法正确地打破由递归引起的嵌套循环。有时我会在我的足迹中获得额外的类别,或者当我认为我已经突破时,一些更深的嵌套类别最终会出现在足迹中。
一个结果可能是这样的。很明显,它并没有终止 b4 处的循环,我不确定为什么会找到两次结果。
b4
FOUND
["c1", "d2", "d3", "b4"]
e2
FOUND
["c1", "d2", "d3", "b4", "e2"]
如果你还可以给我看一个 underscore.js 版本,那就加分了。
JSFiddle 链接 这里...
// Start function
function findCategory(categoryName) {
var trail = [];
var found = false;
function recurse(categoryAry) {
for (var i=0; i < categoryAry.length; i++) {
console.log(categoryAry[i].category);
trail.push(categoryAry[i].category);
// Found the category!
if ((categoryAry[i].category === categoryName) || found) {
console.log('FOUND');
found = true;
console.log(trail);
break;
// Did not match...
} else {
// Are there children / sub-categories? YES
if (categoryAry[i].children.length > 0) {
console.log('recurse');
recurse(categoryAry[i].children);
// NO
} else {
trail.pop();
if (i === categoryAry.length - 1) {
trail.pop();
}
}
}
}
}
return recurse(catalog);
}
console.clear();
console.log(findCategory('b4'));
例如类别对象数组,带有类别对象的嵌套数组。假设嵌套深度未知。
var catalog = [
{
category:"a1",
children:[
{
category:"a2",
children:[]
},
{
category:"b2",
children:[
{
category:"a3",
children:[]
},
{
category:"b3",
children:[]
}
]
},
{
category:"c2",
children:[]
}
]
},
{
category:"b1",
children:[]
},
{
category:"c1",
children:[
{
category:"d2",
children:[
{
category:"c3",
children:[]
},
{
category:"d3",
children:[
{
category:"a4",
children:[]
},
{
category:"b4",
children:[]
},
{
category:"c4",
children:[]
},
{
category:"d4",
children:[]
}
]
}
]
},
{
category:"e2",
children:[
{
category:"e3",
children:[]
}
]
}
]
}
];
试试
function findCategory(categoryName) {
var trail = [];
var found = false;
function recurse(categoryAry) {
for (var i = 0; i < categoryAry.length; i++) {
trail.push(categoryAry[i].category);
// Found the category!
if ((categoryAry[i].category === categoryName)) {
found = true;
break;
// Did not match...
} else {
// Are there children / sub-categories? YES
if (categoryAry[i].children.length > 0) {
recurse(categoryAry[i].children);
if(found){
break;
}
}
}
trail.pop();
}
}
recurse(catalog);
return trail
}
演示:Fiddle
return stmt 确实有效,但请记住,每次循环展开时都会调用它,而这不是您要查看的内容。例子
// global scope
String matchingVariable;
int getMatch(index count, String input, String[] inputs){
if(isValid(input) || count < inputs.length){
// your condition is met and break
// assign your value to global scope variable
matchingVariable = input;
}else if(matchingVariable ==null){
++count
if(count < inputs.length){
getMatch(count, input+inputs[count], inputs)
}
// NOTE RETURN - I WOULDN'T DO THIS
return input;
// doesn't work instead assign the input to global scope variable when a match is found.
}
}
我即兴创作了 @arun-p-johny 回答我的要求,没有嵌套递归函数(每次都会定义,多次调用时效率低下)并且没有外部状态。
在我的例子中,我需要像文件路径一样获取匹配路径。
// Generic function to return matching node path.
// Usage: const path = findMatch(data, key, value);
// Can ignore last 2 params. They will be initialized internally on first call.
function findMatch(entries, key, value, path, tracker) {
if (!path) { path = []; }
if (!tracker) { tracker = { found: false }; }
for (var i = 0; i < entries.length; i++) {
path.push(entries[i].name); // <----- whatever we want in the final returned value
if (entries[i][key] === value) {
tracker.found = true;
return path.join("/");
} else {
if (entries[i].entries) {
findMatch(entries[i].entries, key, value, path, tracker);
if (tracker.found) {
return path.join("/");
}
}
}
path.pop();
}
}
const dirs = [{"name":"web","id":1,"entries":[{"name":"localfiles","id":2},{"name":"remotefiles","id":3,"entries":[{"name":"remote1.js","id":4},{"name":"scripts","id":5,"entries":[{"name":"run.sh","id":6}]}]}]},{"name":"mobile","id":6,"entries":[{"name":"assets","id":7,"entries":[{"name":"images","id":8,"entries":[{"name":"logo.png","id":9},{"name":"banner.png","id":10},{"name":"location.png","id":11}]}]},{"name":"src","id":12,"entries":[{"name":"index.js","id":13}]}]}];
// Partial funtions to mtch by a specific property
const getFilePathById = (dirs, id) => findMatch(dirs, 'id', id);
const getFilePathByName = (dirs, name) => findMatch(dirs, 'name', name);
console.clear();
console.log('getFilePathById:', getFilePathById(dirs, 4));
console.log('getFilePathByName:', getFilePathByName(dirs, 'remote1.js'));
这可以通过接受子键和我们希望返回值由其组成的键来变得更加通用。