每天积累一点点,大厂offer抱回家!
1.使用 TypeScript 语法将没有层级的扁平数据转换成树形结构的数据
const lists=[
{ id: 3, title: '子级2',parentId:1 },
{ id: 2, title: '子级1',parentId:1 },
{ id: 1, title: '父级1' },
{ id: 4, title: '父级2' },
{ id: 5, title: '子级3', parentId: 4 },
{ id: 6, title: '子级4', parentId: 5 },
]
//拿到父级数组
const list2 = lists.filter(it => !it.parentId && it.parentId !== 0)
let res
//递归的方法
const roback1 = (entity1: any, child: any) => {
entity1.forEach(it => {
//给it添加children属性
it.children = []
let en=[]
child.forEach(ch => {
if (ch.parentId && ch.parentId === it.id) {
it.children.push(ch)
en.push(ch)
}
})
//调用自身实现递归
roback1(en,child)
})
res = entity1
}
roback1(list2, lists)
console.log(res)
2.模板解析
const template = "嗨,{{ info.name.value }}您好,今天是星期{{ day.value }}"
const data = {
info: {
name: {
value: "张三",
},
},
day: {
value: "三",
},
}
const render = function(template, data) {
template = template.replace(/{{.*?}}/g, (item) => {
let res = data
const keyArr = item.match(/[a-zA-Z0-9]+/g)
console.log(keyArr)
keyArr.map((key) => {
res = res[key]
})
return res
})
return template
}
console.log(render(template, data))
3.简单实现一个发布 / 订阅模式
class MyEvent {
handlers = {}
$on(type, fn) {
if (!Reflect.has(this.handlers, type)) {
this.handlers[type] = []
}
this.handlers[type].push(fn)
}
$emit(type, ...params) {
if (!Reflect.has(this.handlers, type)) {
throw new Error(`未注册该事件${type}`)
}
this.handlers[type].forEach((fn) => {
fn(...params)
})
}
$remove(type, fn) {
if (!Reflect.has(this.handlers, type)) {
throw new Error(`无效事件${type}`)
}
if (!fn) {
return Reflect.deleteProperty(this.handlers, type)
} else {
const inx = this.handlers[type].findIndex(
(handler) => handler === fn
)
if (inx === -1) {
throw new Error("无效事件")
}
this.handlers[type].splice(inx, 1)
if (!this.handlers[type].length) {
return Reflect.deleteProperty(this.handlers, type)
}
}
}
}
4.类数组和数组有什么区别?
const likeArr = { 0: "我", 1: "喜欢", 2: "你" }
const arr = ["我", "喜欢", "你"]
console.log(likeArr.length)
console.log(arr.length)
console.log(likeArr.slice)
console.log(arr.slice)
console.log(likeArr instanceof Array)
console.log(arr instanceof Array)
5.for in与Object.keys()的区别?
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype = {
sex: "男",
}
var man = new Person("张三", 18)
console.log(Object.keys(man));
for (var key in man) {
console.log(key);
}