1.JSON.stringify JSON.parse方法实现
let deepClone = function (obj) {
return JSON.parse(JSON.stringify(obj));
};
2.用for…in实现遍历和复制
function deepClone(obj) {
let result = typeof obj.splice === "function" ? [] : {};
if (obj && typeof obj === 'object') {
for (let key in obj) {
if (obj[key] && typeof obj[key] === 'object') {
result[key] = deepClone(obj[key]);
} else {
result[key] = obj[key];
}
}
return result;
}
return obj;
}
3.利用数组的Array.prototype.forEach进copy
let deepClone = function (obj) {
let copy = Object.create(Object.getPrototypeOf(obj));
let propNames = Object.getOwnPropertyNames(obj);
propNames.forEach(function (items) {
let item = Object.getOwnPropertyDescriptor(obj, items);
Object.defineProperty(copy, items, item);
});
return copy;
};
第一种方法:
当遇到function,undefined,null时 会忽略这些字段
第二种方法:
当遇到继承问题时, 无法克隆原始对象的继承
如:
function Person(name){
this.name = name;
}
var tang = new Person('miya');
var newtang = deepClone(tang)
tang.constructor === Person //true
newtang.constructor === Person //false
console.log(newtang.constructor) //ƒ Object() { [native code] }
第三种方法:
同Object.assign一样, 第一层深拷贝,往下几层浅拷贝
原文:https://blog.csdn.net/qq_39083004/article/details/80206336