问了二叉树和链表的数据结构是什么,react和vue的基本的父子组件传参(敲代码),还有手写forEach,加上下面这道题。
实现一个函数要求传入id,返回id所在的对象。当时是用递归的方式实现的,但凡是递归都可以用循环来实现。递归效率低,但写起来简单。
const arr = [
{
id: "1",
children: [
{
id: "1-1",
},
],
},
{
id: "2",
children: [
{
id: "2-1",
children: [
{
id: "2-1-1",
},
],
},
{
id: "2-2",
},
],
},
];
// 递归
function findObj(arr, string) {
let obj;
for (let item of arr) {
if (item.id === string) {
obj = item;
} else if (item.children) {
obj = findObj(item.children, string);
}
}
return obj;
}
// 队列
function findObj(arr, string) {
let obj;
while (arr.length > 0 && !obj) {
let item = arr.shift();
if (item.id === string) {
obj = item;
} else if (item.children) {
for (const childItem of item.children) {
if (childItem.id === string) {
obj = childItem;
} else {
arr.push(childItem);
}
}
}
}
return obj;
}
console.log(findObj(arr, "2-1-1"));