定义:
递归是一种编程技术,它是指一个函数在其定义内部调用自身的过程。
特点:
- 一个问题可以分解为更小的问题用同样的方法解决;
- 分解后的子问题求解方式一样,不同的是数据规模变小;
- 存在递归终止条件
作用:
递归拼接树型结构
const rootList = [
{ id: 1, parent: null, text: '菜单1' },
{ id: 11, parent: 1, text: '菜单1-1' },
{ id: 12, parent: 1, text: '菜单1-2' },
{ id: 2, parent: null, text: '菜单2' },
{ id: 21, parent: 2, text: '菜单2-1' },
{ id: 22, parent: 2, text: '菜单2-2' },
{ id: 3, parent: null, text: '菜单3' },
{ id: 31, parent: 3, text: '菜单3-1' }
]
function getTreeList(rootList, id, list) {
for (const item of rootList) {
if (item.parent === id) {
list.push(item)
}
}
for (const x of list) {
x.children = []
getTreeList(rootList, x.id, x.children)
if (x.children.length === 0) {
delete x.children
}
}
console.log('list: ', list);
}
let res = getTreeList(rootList, null, [])
//
求1-100的和
function getSum100(num) {
if (num === 1) {
return 1
} else {
return num + getSum100(num - 1)
}
}
let sum100 = getSum100(100)
console.log('sum100: ', sum100);