数据
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: []
}]
}];
实现方式一
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;
}
}
}
};
实现方式二
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;
}
};
函数执行
方式一
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)}
方式二
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
。