我有一個數據樹,我試圖創建一個遞歸函數來將每個路徑添加到樹中作爲一個字符串數組,以便更好地理解遞歸。我不知道爲什麼我的方法不產生預期通過樹遞歸創建麪包屑列表
var tree = {
\t "name": "home",
\t "children": [
\t \t {
\t \t \t "name": "cars",
\t \t \t "children": [
\t \t \t \t {
\t \t \t \t \t "name": "ford",
\t \t \t \t \t "children": [
\t \t \t \t \t \t {
\t \t \t \t \t \t \t "name": "mustang"
\t \t \t \t \t \t },
\t \t \t \t \t \t {
\t \t \t \t \t \t \t "name": "explorer"
\t \t \t \t \t \t }
\t \t \t \t \t ]
\t \t \t \t }
\t \t \t ]
\t \t },
\t \t {
\t \t \t "name": "food",
\t \t \t "children": [
\t \t \t \t {
\t \t \t \t \t "name": "pizza"
\t \t \t \t }
\t \t \t ]
\t \t }
\t ]
};
var list = [];
var path = [];
function traverse(node) {
if (node.name) {
path.push(node.name)
}
if (!node.children) {
if (path.length) {
list.push(path);
}
return;
} else {
node.children.forEach(function(item) {
traverse(item);
});
}
}
traverse(tree);
console.log(list);
我期待創建的輸出是:
[
["home"],
["home", "cars"],
["home", "cars", "ford"],
["home", "cars", "ford", "mustang"],
["home", "cars", "ford", "explorer"],
["home", "food"],
["home", "food", "pizza"]
]
好一件事你正在存儲遞歸函數外的路徑變量,並且永遠不會重置其值。 – thatidiotguy