递归3种方式

let x = [ { id: 'A', title: '第一层A', children: [ { id: 'A-1', title: '第二层A-1', children: [] } ] }, { id: 'B', title: '第一层B', children: null }, { id: 'C', title: '第一层C', children: [ { id: 'C-1', title: '第二层C-1', children: [] }, { id: 'C-2', title: '第二层C-2', children: [ { id: 'C-2-1', title: '第三层C-2-1', } ] }, { id: 'C-3', title: '第二层C-3', children: null }, { id: 'C-4', title: '第二层C-4', children: [ { id: 'C-4-1', title: '第三层C-4-1', } ] }, ] } ] var list =[] var recursiveFunction = function(){ var str = [] const getStr = function(list){ list.forEach(row=>{ if(row.children && row.children.length){ getStr(row.children) }else { str.push(row) } }) } getStr(x) list = str console.log(list) } recursiveFunction()

var list1 =[] var recursiveFunction1 = function(){ var str1 = [] const getStr1 = function(list1){ list1.forEach(row1=>{ if(!row1.children){ str1.push(row1) }else { getStr1(row1.children)

    }
    })
}
getStr1(x)
list1 = str1
// console.log(list1)

} recursiveFunction1()

var list2 =[] var ids="C-2-1" var recursiveFunction2 = function(data, id){ let res = []; const findIds = (data, temp = []) => { data.forEach((node,index)=>{ if(node.children==null){ node.children=[] } if (node.children.length > 0) { findIds(node.children, temp.concat(index)); } else { if (node.id == id) { temp.push(index) res = temp; } } }) } findIds(data, []); // console.log(res) return res; } recursiveFunction2(x,ids)

transform
JSRUN前端笔记, 是针对前端工程师开放的一个笔记分享平台,是前端工程师记录重点、分享经验的一个笔记本。JSRUN前端采用的 MarkDown 语法 (极客专用语法), 这里属于IT工程师。