三道笔试小题目:拆解url,数组结构转树状结构,深拷贝(包括函数)
1、对 url 中的 query 部分做拆解,返回一个 key - value 形式的 object
使用split对字符串进行切割,再通过遍历配合数组解构可以轻松实现效果
// 入参格式参考:
const url = 'http://sample.com/?a=1&b=2&c=xx&d#hash';
// 出参格式参考:
// const result = { a: '1', b: '2', c: 'xx', d: '' };
function querySearch(url) {
/**
* 此处写代码逻辑
*/
let arr = url.split('?')[1].split('#')[0].split('&');
const result = {};
arr.forEach(item => {
let [key, value = ''] = item.split('=');
result[key] = value;
});
}
const result = querySearch(url);
console.log(result);
2、将数组转化为树状数据结构
// 入参格式参考:
const arr = [
{ id: 1, name: 'i1' },
{ id: 2, name: 'i2', parentId: 1 },
{ id: 4, name: 'i4', parentId: 3 },
{ id: 3, name: 'i3', parentId: 2 },
{ id: 8, name: 'i8', parentId: 7 },
];
// 出参格式可自行设计
function buildTree(arr) {
/**
* 此处写代码逻辑
*/
let dataObjById = {};
arr.map((item, index) => {
dataObjById[item.id] = item;
});
let result = [];
arr.map((item, index) => {
// 子节点根据id获取到父节点对象
let parentNode = dataObjById[item.parentId];
// 如果父节点对象不存在,就是根节点
if (parentNode) {
// 父节点对象存在,则插入子节点对象
if (!parentNode['children']) {
parentNode['children'] = [];
}
parentNode['children'].push(item);
} else {
result.push(item);
}
});
return result;
}
console.log(buildTree(arr));
数组转化为树形结构参考:https://blog.csdn.net/qq_40710228/article/details/105134144
3、深拷贝一个对象,对象可能包含 function
// 入参格式参考:
const originObj = {
a: {
b: {
c: [1, 5, 11, 23, 422],
},
},
d: function () {
console.log('hello world');
},
};
function clone(originObj) {
/**
* 此处写代码逻辑
*/
if (originObj == null) {
return null;
}
// 判断是否为arr类型
let result = Array.isArray(originObj) ? [] : {};
for (let key in originObj) {
if (originObj.hasOwnProperty(key)) {
if (typeof originObj[key] === 'object') {
// 如果是对象,再次调用该方法自身
result[key] = clone(originObj[key]);
} else {
result[key] = originObj[key];
}
}
}
return result;
}
console.log(clone(originObj) === originObj);