前端面试题总结

109 阅读1分钟

image.png

深拷贝和浅拷贝(引用类型数据)

浅拷贝

  • 地址的拷贝,指向的是同一块空间
let obj = {
    name: 'zly',
    age: 18
}
let objNew = obj
objNew.name = 'wyb'
console.log('obj', obj);
console.log('objNew', objNew);
// 输出是一样的

浅拷贝(只拷贝一层)

  • 对象浅拷贝: Object.assign,对于子对象是地址拷贝
let obj = {
    name: 'zly',
    age: 18,
    subObj: {
        name: 'wyb',
        sex: '男'
    }
}
let objNew = Object.assign({}, obj)
objNew.name = 'hjb'
objNew.attr.sex = '女'
console.log('obj', obj);
console.log('objNew', objNew);

输出:
image.png

  • 数组的浅拷贝(只拷贝一层):concat、slice
let arr = [1,2,3, [3,4,5]]
// let brr = arr.concat()
let brr = arr.slice()
arr.push(6)
arr[3].push(6)
console.log(arr);
console.log(brr);

输出:
image.png

深拷贝(完全克隆拷贝)

  • JSON.parse(JSON.stringify(obj))
let obj = {
    name: 'zly',
    age: 18,
    subObj: {
        name: 'wyb',
        sex: '男'
    }
}
let objNew = JSON.parse(JSON.stringify(obj))
objNew.subObj.name = 'hjb'
objNew.name = 'hjb'
console.log('obj', obj);
console.log('objNew', objNew); // 修改新对象不影响原对象的数据

CSS 不定宽高的垂直水平居中(8种)

1. flex

.father { 
    display: flex;
    justify-content: center;
    align-items: center;
}

2. flex + margin

.father {
  dislay: flex;
 }
.son {
  margin: auto;
 }

3. transform + absolute

.father {
  dislay: flex;
 }
.son {
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
 }

4. table-cell

.father {
   display: table-cell;
   text-align: center;
   vertical-align: middle;
 }

5.absolute + 四个方向的值相等

// 这种方法一般用于弹出层,需要设置弹出层的宽高。
.father {
   position: relative;
 }
.son {
    width: 170px;
    height: 20px;
    margin: auto;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
 }

6. grid

.father {
 display: grid;
}
.son {
   align-self: center;
   justify-self: center;
}

7. ::after

.father {
  text-align: center;
}
.father::before {
   content: '';
   display: inline-block;
   vertical-align: middle;
   height: 100%;
}

8.::before

.father {
   text-align: center;
   font-size: 0;
}
.father::before {
   display: inline-block;
   vertical-align: middle;
   font-size: 14px;
   content: '';
   height: 100%;
}