您当前的位置: 首页 >  搜索

暂无认证

  • 1浏览

    0关注

    92582博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

使用递归遍历树形结构的数据,并根据id查询返回对应的数据、搜索、查询、查找、全值

发布时间:2021-09-27 18:35:42 ,浏览量:1

目录
  • 数据
  • 功能函数-1
  • 功能函数-2
  • 函数执行
  • instanceof
  • find
  • 效果演示-小程序码
数据
let treeData = [{ id: 1, aname: '邓稼先', value: '核物理学家', age: 1924, children: [{ id: 11, aname: '袁隆平', value: '杂交水稻育种专家', age: 1930, children: [] }] }, { id: 2, aname: '钱学森', value: '空气动力学家', age: 1991, children: [{ id: 22, aname: '李四光', value: '地质学家', age: 1889, children: [{ id: 222, aname: '于敏', value: '核物理学家', age: 1926, children: [] }] }] }, { id: 3, aname: '华罗庚', value: '数学家', age: 1910, children: [{ id: 33, aname: '钱三强', value: '核物理学家', age: 1913, children: [] }] }]; 
功能函数-1
function tree(data, id) { for (let i = 0; i < data.length; i++) { let item = data[i]; if (item.id === id) { return item; } else { // item.children 不等于 undefined && item.children.length 大于 0 时 if (item.children && item.children.length > 0) { let res = tree(item.children, id); // 当 res = undefined 时不会进入判断中 // 也就是不会return if (res) return res; } } } }; 
功能函数-2
function findItemById(list, id) { // 每次进来使用find遍历一次 let res = list.find((item) => item.id == id); if (res) { return res; } else { for (let i = 0; i < list.length; i++) { if (list[i].children instanceof Array && list[i].children.length > 0) { res = findItemById(list[i].children, id); if (res) return res; } } return null; } }; 
函数执行

功能函数-1

console.log("查询结果:", tree(treeData, 11)); // 查询结果: {id: 11, aname: "袁隆平", value: "杂交水稻育种专家", age: 1930} console.log("查询结果:", tree(treeData, 33)); // 查询结果: {id: 33, aname: "钱三强", value: "核物理学家", age: 1913, children: Array(0)} console.log("查询结果:", tree(treeData, 3)); // 查询结果: {id: 3, aname: "华罗庚", value: "数学家", age: 1910, children: Array(1)} 

功能函数-2

console.log(findItemById(treeData, 33)); // {id: 33, aname: "钱三强", value: "核物理学家", age: 1913, children: Array(0)} console.log(findItemById(treeData, 1)); // {id: 1, aname: "邓稼先", value: "核物理学家", age: 1924, children: Array(1)} console.log(findItemById(treeData, 222)); // {id: 222, aname: "于敏", value: "核物理学家", age: 1926, children: Array(0)} 
instanceof

instanceof运算符用于检测构造函数的prototype属性是否出现在某个实例对象的原型链上。

find

w3school

find方法返回数组中第一个通过测试的元素的值(作为函数提供)。 find方法对数组中存在的每个元素执行一次函数: 如果找到函数返回true值的数组元素,则find返回该数组元素的值(并且不检查剩余值) 否则返回undefined find不对空数组执行该函数。 find不会改变原始数组。

MDN

find方法返回数组中满足提供的测试函数的第一个元素的值。否则返回undefined。 如果需要在数组中找到对应元素的索引,请使用findIndex。 如果需要查找某个值的索引,请使用Array.prototype.indexOf。它类似于findIndex,但只是检查每个元素是否与值相等,而不是使用测试函数。 如果需要查找数组中是否存在某个值,请使用Array.prototype.includes。同样,它检查每个元素是否与值相等,而不是使用测试函数。 如果需要查找是否有元素满足所提供的测试函数,请使用Array.prototype.some。

效果演示-小程序码

2.0.0X

关注
打赏
1653961664
查看更多评论
立即登录/注册

微信扫码登录

0.3497s