对象的深度克隆方法
function deepclone(obj) {
if (typeof obj === 'object' && obj !== null) {
if (obj instanceof array) {
let newarr = [];
obj.foreach(item => {
newarr.push(item);
})
return newarr;
} else if (obj instanceof object) {
let newobj = {};
for (let key in obj) {
if (obj[key] instanceof (object) && !obj[key] instanceof function) {
console.log(key);
newobj[key] = arguments.callee(obj[key]);
} else {
newobj[key] = obj[key];
}
}
return newobj;
}
} else {
return;
}
}
方法2:方法1的简化版
function deepclone2(obj) {
if (typeof obj === 'object' && obj !== null) {
let result = obj instanceof array [] : {};
for (let key in obj) {
result[key] = typeof obj[key] === 'object' && !obj[key] instanceof function arguments.callee(obj[key]) : obj[key];
}
return result;
} else {
return;
}
}
方法3:借助object.assign()和object.create()
function deepclone3(obj) {
let proto = object.getprototypeof(obj);
let result = object.assign({}, object.create(proto), obj);
return result;
}
上一篇: vue-cli脚手架自动生成项目