樹的全部展開操作飒焦,一般需要獲取到所有的樹的組件節(jié)點(diǎn)key
樹的數(shù)據(jù)結(jié)構(gòu):
interface TNode {
title: string;
key: number;
children: TNode[];
}
1尸红、查看所有的父節(jié)點(diǎn)
function getAllParentKeys(list: TNode[]) {
const keys: number[] = [];
list.forEach(({ key, children }) => {
if (children.length > 0) {
keys.push(key, ...getAllParentKeys(children));
}
});
return keys;
}
2、查找某個指定節(jié)點(diǎn)的所有祖先節(jié)點(diǎn)
// 找到某個節(jié)點(diǎn)的所有祖先節(jié)點(diǎn)
function findParentKeys(list: TNode[], childKey: number) {
const resultKey: number[] = [];
canFindKey(list, childKey, resultKey);
return resultKey;
}
function canFindKey(list: TNode[], childKey: number, result: number[]) {
let canFind = false;
// 這里的遍歷需要注意!使用some return true可以跳出some循環(huán)
// 如果使用forEach return只能跳出當(dāng)前循環(huán)赖瞒,但是不能終止forEach,可以使用try catch終止
list.some(({ key, children }) => {
if (key === childKey) {
canFind = true;
return true;
}
if (children.length > 0) {
result.push(key);
canFind = canFindKey(children, childKey, result);
if (canFind) {
return true;
}
result.pop();
}
return false;
});
return canFind;
}