浅拷贝
function simpleClone(target) {
const type = Object.prototype.toString.call(target).replace('[object ','').replace(']', '').toLowerCase();
if(type === 'object') {
return Object.assign({},target);
} else {
return target;
}
}
深拷贝
function deepClone(target, map = new Map()) {
const type = Object.prototype.toString.call(target).replace('[object ','').replace(']', '').toLowerCase();
if(typeof target === 'object') {
if(type === 'date') {
return new Date(target);
}
if(type === 'regexp') {
return new RegExp(target);
}
let cloneTarget = Array.isArray(target) ? [] : {};
if(map.get(target)) return target;
map.set(target, cloneTarget);
for(let k in target) {
cloneTarget[k] = deepClone(target[k], map);
}
return cloneTarget;
} else {
return target;
}
}
测试
var arr = [
{ a: new Date(), aa: new RegExp('\\w+'), aaa: function() { console.log('aaa function') } },
{ b: 'qwe' },
{ c: [null, undefined] },
{ d: [{ da: 1, db: { dba: 123 }}] }
]
deepClone(arr);