方法一:用JSON
const b = JSON.parse(JSON.stringify(a));//先将a序列化,再反序列化赋值给b
JSON深拷贝的缺点:
1.不支持日期、正则、undefined、函数等类型
2.不支持引用类型
方法二:使用递归
const deepClone = (a, cache) => {
if (!cache) cache = new Map() // 缓存不能全局,最好临时创建并递归传递
if (a instanceof Object) {
if (cache.get(a)) return cache.get(a)
let result = undefined
if (a instanceof Function) {
//判断普通函数还是箭头函数
if (a.prototype) { //如果函数有prototype就是普通函数
result = function () { return a.apply(this, arguments) }
} else { //箭头函数(箭头函数没有this)
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)
console.dir(b)
b.self === b // true
b.self = 'hi'
a.self !== 'hi' //true