Deepcopy in Javascript
2021-06-10 03:03
标签:key 实现 java 通过 asc lodash name console tin 2.Json 注意: 无法实现对象中方法的深拷贝 3.Object.assign() 4.Object.create() 改变了对象的结构。同时对引用类型也是浅拷贝,只复制一层 Deepcopy in Javascript 标签:key 实现 java 通过 asc lodash name console tin 原文地址:https://www.cnblogs.com/Nullc/p/14473455.html
没问题function deepClone(obj) {
var target = {};
for(var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) { // 如果obj有key这个属性的话
if (typeof obj[key] === ‘object‘) {
target[key] = deepClone(obj[key]);
} else {
target[key] = obj[key];
}
}
}
return target;
}
JSON.parse(JSON.stringify(obj))
通过Object.assign(destination, [src1, src2, ...])拷贝
可以合并多个对象的属性。
注意: 当对象只有一级属性为深拷贝;
当对象中有多级属性时,二级属性后就是浅拷贝function deepCopy(obj) {
var copy = Object.create(Object.getPrototypeOf(obj));
var propNames = Object.getOwnPropertyNames(obj);
propNames.forEach(function(name) {
var desc = Object.getOwnPropertyDescriptor(obj, name);
Object.defineProperty(copy, name, desc);
});
return copy;
}
var obj1 = { a: 1, b: {bc: 50, dc: 100, be: {bea: 1}} };
var obj2 = deepCopy(obj1);
console.log(obj2)
obj1.a = 20;
console.log(obj1)
console.log(obj2)
//Object {a: 1, b: Object}
//Object {a: 20, b: Object}
//Object {a: 1, b: Object}
5.lodash._deepcopy()