我有一個嵌套資料結構,我想創建一個遞回函式,給定物件的名稱引數,它將回傳父物件的名稱引數。
有幾個相關的問題,但是,答案并不能解釋為什么我的功能getParentName不起作用。
為什么getParentName不作業?
const nestedData = {
name: "parent",
children: [{ name: "child", children: [{ name: "grandchild" }] }],
};
function getParentName(nested, name) {
if (nested.children && nested.children.map((d) => d.name).includes(name)) {
return nested.name;
} else if (nested.children) {
nested.children.forEach((child) => {
return getParentName(child, name);
});
}
return undefined; //if not found
}
//The parent of "grandchild" is "child" - but the function returns undefined
const parentName = getParentName(nestedData, "grandchild");
為什么這個函式找不到父級?
uj5u.com熱心網友回復:
您的答案的問題是.forEach忽略了return價值。return您的else if分支沒有。.forEach僅用于副作用。考慮使用生成器,它可以更輕松地表達您的解決方案 -
function* getParentName({ name, children = [] }, query) {
for (const child of children)
if (child.name === query)
yield name
else
yield *getParentName(child, query)
}
const data = {
name: "parent",
children: [{ name: "child", children: [{ name: "grandchild" }] }],
}
const [result1] = getParentName(data, "grandchild")
const [result2] = getParentName(data, "foobar")
const [result3] = getParentName(data, "parent")
console.log("result1", result1)
console.log("result2", result2)
console.log("result3", result3)
答案是undefined如果沒有找到匹配的節點或者匹配的節點沒有父節點 -
result1 child
result2 undefined
result3 undefined
需要注意[]來捕獲單個結果。這是因為生成器可以回傳 1 個或多個值。如果你不喜歡這種語法,你可以撰寫一個通用first函式,它只從生成器中獲取第一個值 -
function first(it) {
for (const v of it)
return v
}
const result1 = first(getParentName(data, "grandchild"))
const result2 = first(getParentName(data, "foobar"))
const result3 = first(getParentName(data, "parent"))
這種方法的優點很多。您的嘗試使用.map并且.includes兩者都children完全迭代。在另一個分支中,.forEach使用了它也對所有分支進行了詳盡的迭代children。這種方法避免了不必要的.map,.includes而且在讀取第一個值后立即停止。
uj5u.com熱心網友回復:
@Mulan 回答了我的問題,指出函式失敗是因為 .forEach() 中的 return 陳述句被忽略了。然后,他們提供了一個生成器功能作為更好的選擇。
為了清楚起見,這里是原始功能的最小更改形式。forEach() 被替換為 (for x of array) 回圈。此外,僅回傳真值。
function getParentName(nested, name) {
if (nested.children && nested.children.some((d) => d.name === id)) {
return nested.name;
} else if (nested.children) {
for (const child of node.children) {
const result = getParentName(child, id);
if (result) return result;
}
}
return undefined; //if not found
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/461004.html
標籤:javascript 递归 嵌套的
