【前端面试】 - 常见笔试题

157 阅读1分钟

1.计算数组的层级

    const arr = [1,2,[1,[1,2]],4]
    let num = 0;
    function getArrLevelNum(arr){
        for(const item of arr){
            if(isArray(item)){
                num++
                getArrLevelNum(item)
            }
        }
        return num
    }

2.将数组转换为数结构

    const arr = [
        {id:0,name:'测试',pid:null},
        {id:1,name:'测试',pid:0},
        {id:2,name:'测试',pid:1},
        {id:3,name:'测试',pid:2},
        {id:4,name:'测试',pid:2},
    ]
    function arrToTree(arr){
        let map = {}
        let result = []   
        for(const item of arr){
            map[item.id] = item 
        }
        arr.forEach(item => {
            const parent = map[item.pid]
            if(parent){
                (parent.children ??= []).push(map[item.id])
            }else{
                result.push(item)
            }
            pid和id相等时,当前项即为找到的父元素,找到了pid对应的父元素就放入children 
            否则就放入根目录result中。
        })
        return result
    }
   
    console.log(arrToTree(arr))

3.将对象中的小驼峰key值转换为大驼峰

      const obj = {
        myName: '测试',
        myAge: 28
      }
      function transFormObj(obj) {
        let newObj = {}
        for (let key in obj) {
          let str = key[0].toUpperCase() + key.substring(1)
          newObj[str] = obj[key]
        }
        return newObj
      }
      console.log(transFormObj(obj))
      ----------------------------------------------
    修正:上述写法未考虑到对象中有对象的场景,思路 递归
    
```js
     function transFormObj(obj) {
        for (let key in obj) {
          if (Object.prototype.toString.call(obj[key]) === '[object Object]') {
            transFormObj(obj[key])
          }
          let str = key[0].toUpperCase() + key.substring(1)
          obj[str] = obj[key]
          delete obj[key]
        }
        return obj
      }