递归遍历
递归一般是在函数里面把函数自己给调用一遍,通过每次调用改变条件,来结束循环。
递归在数据格式一致,在数据层级未知的情况下,比普通的遍历更有优势。
应用场景
- 树 🌳
- 排序
const data = [
{
name: "所有物品",
children: [
{
name: "水果",
children: [{ name: "苹果", children: [{ name: "青苹果" }, { name: "红苹果" }] }]
},
{
name: "主食",
children: [{ name: "米饭", children: [{ name: "北方米饭" }, { name: "南方米饭" }] }]
},
{
name: "生活用品",
children: [
{ name: "电脑类", children: [{ name: "联想电脑" }, { name: "苹果电脑" }] },
{ name: "工具类", children: [{ name: "锄头" }, { name: "锤子" }] },
{ name: "生活用品", children: [{ name: "洗发水" }, { name: "沐浴露" }] }
]
}
]
}
];
//递归遍历实现
let recursiveFunction = function () {
let str = "";
const getStr = function (list) {
list.forEach(function (row) {
if (row.children) {
getStr(row.children);
} else {
str += row.name + ";";
}
});
};
getStr(data);
console.log(str);
};
recursiveFunction();
//输出:青苹果;红苹果;北方米饭;南方米饭;联想电脑;苹果电脑;锄头;锤子;洗发水;沐浴露;