场景一:处理后端api接口数据
后端返回的接口数据,实现多级遍历,拿到每次层最后一个数据
拿出的数据 青苹果 红苹果 北方米饭 南方米饭 联想电脑 苹果电脑 锄头 锤子 洗发水 沐浴露
var 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: "沐浴露"}]}
]
}
]
}]
实现思路:
通过判断是否还有
children
,没有就代表是最后一级了,有就继续把children
这个list
传给函数继续遍历,最后就得到了我们想要的数据。
var recursiveFunction = function () {
var str = ''
const getStr = function (list) {
list.forEach(function (row) {
// row是每一层的对象
console.log(row);
if (row.children) {
// 如果存在row.children说明不是最后一层,调用上面的函数继续向下寻找
getStr(row.children)
} else {
str += row.name + ";"
}
})
}
getStr(data)
console.log(str)
}
recursiveFunction()
优点:
递归遍历,理论上,只要内存够用,你能实现任意层级的遍历或者遍历未知层级,但缺点也很明显,没一个层级里面需要有固定的数据格式,否则无法遍历。
场景二:递归实现深拷贝
如下代码,实现对o数组的深拷贝给b,然后修改0中的数据,b的数据不受影响
const o = [1, 2, 3, 4, 5]
function clone(o) {
var temp = {}
for (var key in o) {
if (typeof o[key] == 'object') {
temp[key] = clone(o[key])
} else {
temp[key] = o[key]
}
}
return temp
}
b = clone(o)
o[1] = 99
console.log(o, b);