个人自学前端42-杂谈-vue中树的深度遍历和广度遍历

一. 深度遍历

	// res 遍历的数组,id 判断条件
	console.log(this.setMenuId(res,id))
    setMenuId(res, id) {
      for (let i = 0; i < res.length; i++) {
	  	// 条件判断
        if (res.id == id) {
          return urlMenuId
        }
		// 如果有 children 则 继续遍历
        if (res[i].children) {
          this.setMenuId(res[i].children, id)
          continue
        }
      }
    },

二. 广度遍历

    // res 遍历的数组,id 判断条件
	console.log(this.setMenuId(res,id))
    setMenuId(res, id) {
      // 深拷贝原始数据
      const dataSource = JSON.parse(JSON.stringify(res))
      const arr = []
      // 每一层的数据都 push 进 arr
      arr.push(...dataSource)
      // arr 动态增加长度
      for (let i = 0; i < arr.length; i++) {
        const curData = arr[i]
        // 条件判断
        if (curData.id == id) {
          return curData.id
        }
        // 如果有 children 则 push 进 arr 中待搜索
        if (curData.children) {
          arr.push(...curData.children)
        }
      }
      // 没有搜索到结果,默认空数组
      return []
    },
posted @ 2022-04-09 16:01  暗鸦08  阅读(185)  评论(0)    收藏  举报