什么是深拷贝?
深拷贝就是相对与浅拷贝而言的,最主要的差异体现在引用类型上,从本质上讲就是浅拷贝只简简单单地把栈当中的引用地址拷贝了一份,所以当你修改新拷贝出来的值的时候,被拷贝的对象也会被你修改掉;而深拷贝是会在堆内存当中为新对象建立空间,所以被拷贝的对象就不会被无缘无故地被修改掉了。
手写深拷贝
方法一
const b = JSON.parse(JSON.stringify(a))
这个方法有如下缺点:
- 不支持 Date、正则、undefined、函数等数据
- 不支持引用(即环状结构)
- 必须说自己还会方法二
方法二:使用递归
要点:
- 递归
- 判断类型
- 检查环
- 不拷贝原型上的属性
const deepClone = (a, cache) => {
if(!cache){
cache = new Map() // 缓存不能全局,最好临时创建并递归传递
}
if(a instanceof Object) { // 不考虑跨 iframe
if(cache.get(a)) { return cache.get(a) }
let result
if(a instanceof Function) {
if(a.prototype) { // 有 prototype 就是普通函数
result = function(){ return a.apply(this, arguments) }
} else {
result = (...args) => { return a.call(undefined, ...args) }
}
} else if(a instanceof Array) {
result = []
} else if(a instanceof Date) {
result = new Date(a - 0)
} else if(a instanceof RegExp) {
result = new RegExp(a.source, a.flags)
} else {
result = {}
}
cache.set(a, result)
for(let key in a) {
if(a.hasOwnProperty(key)){
result[key] = deepClone(a[key], cache)
}
}
return result
} else {
return a
}
}
const a = {
number:1, bool:false, str: 'hi', empty1: undefined, empty2: null,
array: [
{name: 'frank', age: 18},
{name: 'jacky', age: 19}
],
date: new Date(2000,0,1,20,30,0),
regex: /\.(j|t)sx/i,
obj: { name:'frank', age: 18},
f1: (a, b) => a + b,
f2: function(a, b) { return a + b }
}
a.self = a
const b = deepClone(a)
b.self === b // true
b.self = 'hi'
a.self !== 'hi' //true
手写数组去重
- 使用计数排序的思路,缺点是只支持字符串
- 使用 Set(面试已经禁止这种了,因为太简单)
- 使用 Map,缺点是兼容性差了一点
var uniq = function(a){
var map = new Map()
for(let i=0;i<a.length;i++){
let number = a[i] // 1 ~ 3
if(number === undefined){continue}
if(map.has(number)){
continue
}
map.set(number, true)
}
return [...map.keys()]
}