欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

对象的深度克隆方法

程序员文章站 2022-07-21 15:50:46
对象的深度克隆方法 function deepclone(obj) { if (typeof obj === 'object' && obj !== null) {...
对象的深度克隆方法

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;

}