【发布时间】:2021-06-24 22:44:31
【问题描述】:
我有一个这样的对象:
const obj = {
name: 'john',
children: [
{
name: 'Foo'
},
{
name: 'Bar',
children: [
{
name: 'Doe'
}
]
}
]
}
我必须创建一个函数来查找具有指定名称的对象。 我的代码可以找到具有名称的对象,但它不返回该对象。
const search = (node, name) => {
return searchInObj(node, name);
};
const searchInObj = (obj, name) => {
if (obj.name === nodeName) {
return obj;
} else {
if (obj.children) {
searchInArr(obj.children, name);
}
}
};
const searchInArr = (arr, name) => {
for (let i = 0; i < arr.length; i++) {
searchInObj(arr[i], name);
}
};
如果我放
console.log(search(obj, 'Doe')) // return undefined
如果我寻找john,它就可以工作
【问题讨论】:
-
您遗漏了一些
return语句 -
你试过调试你的函数吗?另外,我会使用
Array.prototype.some在 children 数组中搜索,而不是在那里添加searchInArr。然后递归将在 searchInObj 中进行。此外,undefined作为返回值表示缺少返回语句,正如 Quentin 指出的那样。
标签: javascript function object