当前位置: 首页 > Web前端 > JavaScript

前端js编程题总结

时间:2023-03-27 16:42:51 JavaScript

1.将数组压扁,将下面数据的多层树结构处理成只有一层子数据的结构=[{name:"About",path:"/about",children:[{name:"AboutUS",path:"/about/us"},{name:"AboutComp",path:"/about/company",children:[{name:"AboutCompA",path:"/about/company/A",children:[{name:"AboutCompA1",path:"/about/company/A/1"}]}]}]}]//处理后的结构[{name:"About",path:"/about",children:[{name:"AboutUS",path:"/about/us"},{name:"AboutComp",path:"/about/company",},{name:"AboutCompA",path:"/about/company/A"},{name:"AboutCompA1",path:"/about/company/A/1"}]}]代码实现://递归遍历实现varrecursiveFunction3=function(){varaa=[]varcc=[]constgetStr=function(data){data.forEach(item=>{aa.push({name:item.name,path:item.path})if(item.children?.length){让children=getStr(item.children)}})}getStr(data)cc.push({name:aa[0].name,path:aa[0].path,children:aa.slice(1)})//console.log(cc)}recursiveFunction3()代码在前面的基础上进行了优化:varrecursiveFunction4=function(){varaa=[]constgetStr=function(data){data.forEach(item=>{aa.push({name:item.name,path:item.path})if(item.children?.length){letchildren=getStr(item.children)}})}getStr(data[0].children)//...expansion操作符因为前两项数据没有变化所以直接使用copy,然后替换children的最后一项aa=[{...data[0],children:aa}]console.log(aa)}recursiveFunction4()//基于recursiveFunction3()优化,还有一种基于大哥的方案,代码如下如下://写了一段代码,可以自由定义一个flatlevel,level代码不是flatlevelfunctionflatTree(data,level=0,index=0){letresult=[],obj;data.forEach(item=>{result.push(obj={name:item.name,path:item.path})if(item.children?.length){letchildren=flatTree(item.children,level,index+1)if(level>index){obj.children=children}else{result=result.concat(children)}}})returnresult}降维数组//使用[].concat.apply实现降维vararr=[[1,2],[3,4]];函数Jw(obj){console.log(Array.prototype.concat.apply([],obj))returnArray.prototype.concat.apply([],obj);}jw(arr);//如果concat方法的参数是一个元素,则直接将该元素插入到新数组中;如果参数是一个数组,数组的每个元素都会被插入到新的数组中functionreduceDimension(arr){letret=[];for(leti=0;ib.flag-a.flag);console.log(r);//[//{id:10,flag:true},//{id:6,flag:true},//{id:5,flag:false},//{id:9,flag:false}//]

最新推荐
猜你喜欢