文章目录
JavaScript 深拷贝
采用递归方式设置深拷贝函数:
function deepCopy(obj) {
if (typeof obj !== 'object') return;
let newObj = obj instanceof Array ? [] : {};
for (let key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
}
}
return newObj;
}
使用:
console.log(deepCopy({ name: 'anny' }));