题目1、手写 flat (我真的会谢,第二次遇到这个题了,还是忘记了)
基础知识:arr.flat ,depath 参数展开几层
depath<0,返回原数组
depath == Infinity 展开一维数组
ok,上代码
function myFlat(arr,depath){
if(depath === 0) {
return array.slice();
}
// 使用reduce 来遍历数组并扁平化
return array.reduce((acc,item)=>{
if(Array.isArray(item) && depath >0){
return acc.concat(flat(item,depath-1))
} else{
return acc.concat(item)
}
},[])
}
const arr = [1,2,3,4,[1,2,3,[1,2,3,4,[1,2,3]]],5,'string',{name:'前端收割机'}]
console.log( myFlat(arr,3))
题目2、数据去重
(下面是我的答案,我觉得是对的,有错误请指正)
function unique(arr){
const target =[]
const res={}
arr.forEach(el => {
if(typeof el =='object'){
const str = JSON.stringify(el)
if(!res[str]){
target.push(el)
res[str] = el
}
}else if(!target.includes(el)){
target.push(el)
}
});
return target
}
const obj1 = {age:12}
const arr =[123,'123',{},{},null,undefined,void 0,"abc","abc",obj1,obj1,{age:12},{age:12,name:'lyn'}]
console.log(unique(arr))
}
题目3、使用React组件和一个hooks 实现一个N秒倒计时组件,从倒计时结束时可传入的一个回调函数。 interface IPropos(func()=>void; timer:number)
const useCountDown=(props:IPropos)=>{}
const Countdown:FC=({time,func})=>{
const {} = useCountDown();
... }
(其实我这个我也不会)