js 递归
我们前端主管老王教的。
const treeData = [ { title: '1', key: 'key-0', children: [ { title: '1-1', key: 'key-0-0', children: [ {title: '1-1-1', key: 'key-0-0-0'}, { title: '1-1-2', key: 'key-0-0-2', children: [ {title: '1-1-2-1', key: 'key-0-0-0'}, ], }, ], }, { title: '1-2', key: 'key-0-2', }, ], }, ]; // 获取第二级title. /* * index 当前索引。 * t 遍历的层级。 * cb 回调函数,拿到对应的参数。 */ const list = []; function c(arr, index = 0, t = 0, cb) { const o = arr[index]; if (o) { if (Array.isArray(o.children) && o.children.length) { c(o.children, 0, t + 1, cb); } if (t === 3) { // 递归的层级,拿到层级里面的数据。 cb && cb(o.title); // 获取第三级的title。 } list.push(o.title); // 获取所有的title。 c(arr, index + 1, t, cb); } } c(treeData, 0, 0, (title) => { console.log(title, 'title'); }); console.log(list, 'list');

浙公网安备 33010602011771号