当前位置: 移动技术网 > IT编程>网页制作>CSS > 对象的深度克隆方法

对象的深度克隆方法

2018年12月10日  | 移动技术网IT编程  | 我要评论
对象的深度克隆方法

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;

}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网