【发布时间】:2019-02-04 12:24:17
【问题描述】:
我有一个问题,我无法解决问题。如果我在一个可能无限的数据结构中寻找具有特定ID 的对象,我该如何循环遍历它,直到找到我需要的对象并返回该对象?
如果这是我的数据的样子,我怎样才能使用id === 3 获取对象?
{
id: 0,
categories: [
{
id: 1,
categories: [
{
id: 2,
categories: [ ... ]
},
{
id: 3,
categories: [ ... ]
},
{
id: 4,
categories: [ ... ]
},
]
}
]
}
我尝试了以下方法:
findCategory = (categoryID, notesCategory) => {
if (notesCategory.id === categoryID) {
return notesCategory;
}
for (let i = 0; i < notesCategory.categories.length; i += 1) {
return findCategory(categoryID, notesCategory.categories[i]);
}
return null;
};
但这永远不会到达id === 3。它使用id: 2 检查对象,然后返回null。它永远不会到达带有id: 3 的对象。
【问题讨论】:
标签: javascript recursion