ts版本:
const deepClone = (obj: any) => {
if (typeof obj !== 'object' || obj === null) {
return obj
}
let copy: any
if (obj instanceof Date) {
copy = new Date(obj)
} else if (obj instanceof RegExp) {
copy = new RegExp(obj)
} else if (obj instanceof Function) {
copy = function () {
// eslint-disable-next-line prefer-rest-params
return obj.apply(this, arguments)
}
} else if (typeof obj === 'symbol') {
copy = Object(Symbol.prototype.valueOf.call(obj))
} else if (Array.isArray(obj)) {
copy = []
for (let i = 0; i < obj.length; i++) {
copy[i] = deepClone(obj[i])
}
} else {
copy = {}
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
copy[key] = deepClone(obj[key])
}
}
}
return copy
}
js版本:
function deepClone(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj
}
let copy
if (obj instanceof Date) {
copy = new Date(obj)
} else if (obj instanceof RegExp) {
copy = new RegExp(obj)
} else if (obj instanceof Function) {
copy = function () {
return obj.apply(this, arguments)
}
} else if (obj instanceof Symbol) {
copy = Object(Symbol.prototype.valueOf.call(obj))
} else if (obj instanceof Array) {
copy = []
for (let i = 0; i < obj.length; i++) {
copy[i] = deepClone(obj[i])
}
} else {
copy = {}
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = deepClone(obj[key])
}
}
}
return copy
}
以下给出实例验证:
// 定义一个复杂对象
const complexObj = {
name: 'Alice',
date: new Date(),
regex: /abc/g,
func: function() {
console.log('Hello!');
},
arr: [1, 2, 3],
symbol: Symbol('foo')
};
// 执行深拷贝
const copiedObj = deepClone(complexObj);
// 修改对象属性
copiedObj.name = 'Bob';
copiedObj.date.setDate(10);
copiedObj.regex = /def/i;
copiedObj.func = function() {
console.log('Hi!');
};
copiedObj.arr.push(4);
copiedObj.symbol = Symbol('bar');
// 对比原始对象和修改后的对象
console.log('Original Object:', complexObj);
console.log('Modified Object:', copiedObj);
打印结果如下: