你不知道的js递归技巧

2019-06-03  本文已影响0人  李贵功

递归找对应的节点

要求如下输入一个id, 找出对应的id所对应的结构

var arr =[
    {id: 1,children: []},
    {id: 2,children: []},
    {id: 3,children: []},
    {id: 4,children: []},
    {id: 5,children: []},
    {
      id: 6,
      children: [
        {
          id: 7,
          children: [{id: 9, children:[]}]
        },{
          id: 8,
          children: []
        }
      ]
    },
  ];
  
  
  方法如下: 
  function digui(arr, id) {
    for(let i = 0; i< arr.length; i++) {
      if(arr[i].id === id){
        return arr[i]
      } else {
        if(arr[i].children.length !== 0){
          return digui(arr[i].children, id)
        }
      }
    }
  }
  
console.log(digui(arr, 9));   //{id: 9, children:[]}
console.log(digui(arr, 6));   
// 结果:  
//    {
//      id: 6,
//      children: [
//        {
//          id: 7,
//          children: [{id: 9, children:[]}]
//        },{
//          id: 8,
//          children: []
//        }
//      ]
//    }

递归找到没有children的所有子节点name

var data = [
    {
      name: "所有物品",
      children: [
        {
          name: "水果",
          children: [{name: "苹果", children: [{name: '青苹果',children: [{name: '北方米饭'}, {name: '南方米饭'}]}, {name: '红苹果'}]}]
        },
        {
          name: '主食',
          children: [
            {name: "米饭"}
          ]
        },
        {
          name: '生活用品',
          children: [
            {name: "电脑类", children: [{name: '联想电脑'}, {name: '苹果电脑'}]},
            {name: "工具类", children: [{name: "锄头"}, {name: "锤子"}]},
            {name: "生活用品", children: [{name: "洗发水"}, {name: "沐浴露"}]}
          ]
        }
      ]
    }]
    
    function didui(arr) {
      let arrList = ''
      function f(arr) {
        arr.forEach(item => {
          if(item.children) {
            arguments.callee(item.children)
          } else {
            arrList += item.name + ';';
          }
        })
      }
      f(arr)
      return arrList;
    }

  console.log(didui(data));  //北方米饭;南方米饭;红苹果;米饭;联想电脑;苹果电脑;锄头;锤子;洗发水;沐浴露;

上一篇下一篇

猜你喜欢

热点阅读