之所以特意写一篇帖子就是想问一下,一般这种编程题放到问答题是什么心态呀,他不方便改,我也不方便写,虽说可以考验我debug能力或者对API的熟练度,但是这么多卷子他们真的会去改吗,我有bug他们真的看得出来吗。。
// 1.数组转树,笔试的时候少写了异步map.get()为空的判断 const nodes = [{id:1,parentId:null,name:'广东'},{id:2,parentId:1,name:'深圳'},{id:3,parentId:1,name:'杭州'}] function transformTree(nodes){ let map = new Map() let root = null for(let i=0;i<nodes.length;i++){ // 记下parentId对应的结点数组 if(nodes[i].parentId == null){ root = nodes[i] continue } let list = map.get(nodes[i].parentId)?map.get(nodes[i].parentId):new Array() list.push(nodes[i]) map.set(nodes[i].parentId,list) } // 找到对应父亲id的结点们 const deepSearch = function(id){ let arr = [] if(!map.get(id)) return for(let x of map.get(id)){ let obj = {} obj.id = x.id obj.name = x.name // obj.children = deepSearch(x.id) arr.push(obj) } return arr } let rootObj = {} rootObj.id = root.id rootObj.name = root.name rootObj.children = deepSearch(root.id) return rootObj } console.log(transformTree(nodes))
// 2.数组去重,笔试的时候有一个数组名arr没改回来,JSON.stringify写成了stringly哈哈,并且这里要用toString()才对的上样例,不过很扯,{a:1}==={a:2}?[1,2,3]==="1,2,3"? // in :[123,"webank",[1,2,3],"123",{a:1},"tencent",123,[1,2,3],{a:2}] // out:[123,"webank",[1,2,3],"123",{a:1},"tencent"] // 关键点,数组与对象的去重,笔试的时候采取了Json.stringify()转换存储,好像应该用toString()方法 let initArr = [123,"webank",[1,2,3],"123",{a:1},"tencent",123,[1,2,3],{a:2}] function deal(arr){ let map = new Map() let newArr = [] for(let i=0;i<arr.length;i++){ let x = typeof arr[i] == 'object'?arr[i].toString():arr[i] if(map.get(x)) continue //map里存在了,不操作 map.set(x,1) newArr.push(arr[i]) } return newArr } let newArr = deal(initArr) console.log(newArr)
// 3.求两个日期中间的有效日期,笔试的时候for的一个;手抖写成了:,monthArr的声明没写成let,习惯性写了const // in:2020-9-29,2020-10-3 // out:['2020-9-29','2020-9-30','2020-10-1','2020-10-2','2020-10-3'] // 这里采用模拟的形式,Date()类的API有点忘了,不知道能不能直接通过API实现 function deal(dateA,dateB){ let ansArr = [] let [yearA,monthA,dayA] = dateA.split('-') yearA=parseInt(yearA); monthA=parseInt(monthA);dayA=parseInt(dayA); let [yearB,monthB,dayB] = dateB.split('-') yearB=parseInt(yearB); monthB=parseInt(monthB);dayB=parseInt(dayB); for(let year=yearA;year<=yearB;year++){ let monthArr = [] if((year%4==0 && year%100!=0) || (year%400==0)) monthArr=[31,29,31,30,31,30,31,31,30,31,30,31] //闰年 else monthArr=[31,28,31,30,31,30,31,31,30,31,30,31] //非闰年 let monthStart = year==yearA?monthA:1 //与起始年同一年就按给定的起始月走,否则从1月开始走 let monthEnd = year==yearB?monthB:12 //与结尾年同一年就按给定的最终月走,否则走到12月 for(let month=monthStart;month<=monthEnd;month++){ let dayStart = (year==yearA&&month==monthA)?dayA:1 //与起始年月都相同就按给定的天走,否则从1号开始走 let dayEnd = (year==yearB&&month==monthB)?dayB:monthArr[month-1] //与结尾年月都相同就按给定的天结束,否则走到月底 for(let day=dayStart;day<=dayEnd;day++){ let date = `${year}-${month}-${day}` ansArr.push(date) } } } return ansArr } let dateArr = deal("2020-9-29","2020-10-3") console.log(dateArr)