什么是遞歸
簡單的說就是在函數(shù)內(nèi)部調(diào)用此函數(shù)
function foo() {
foo()
}
//僅作示例狼忱,真這么寫就堆棧溢出了
怎么用遞歸
- 大問題分解為相同的小問題
- 設(shè)置明確的終止條件
- 雖然是重復(fù)運(yùn)行同一函數(shù)但每一步都會更接近終止條件只恨。
//求1到n的和
function sum(n){
if(n==1) return 1;
return sum(n-1) + n;
}
實(shí)際應(yīng)用
let arr = [
{
_id: '5bf93b99f18bee3ccce96389',
name: '吃飯',
children: [{_id: '5bf93b99f18bee3ccce9638a', name: '午飯',children: []}] },
{_id: '5bf93b99f18bee3ccce96388',
name: '睡覺',
children: [] }
]
樹狀結(jié)構(gòu)卑雁,需要把每一個(gè)對象的id與name取出并重新存入一維數(shù)組。也就是不能有children了
function extract (arr) {
let array = []
;(function iteration (arr) {
for (const element of arr) {
array.push({ id: element._id, name: element.name })
if (element.hasOwnProperty('children') && element.children.length > 0) {
iteration(element.children)
}
}
})(arr)
return array
}
運(yùn)行一下結(jié)果正確哪替,多套幾層也能成功展開阱扬。
[ { id: '5bf93b99f18bee3ccce96389', name: '吃飯' },
{ id: '5bf93b99f18bee3ccce9638a', name: '午飯' },
{ id: '5bf93b99f18bee3ccce96388', name: '睡覺' } ]