- 深拷贝:修改复制对象,原始对象不会变化
- 浅拷贝:修改复制对象,原始对象也变化
方式:
- 遍历赋值
- Object.create()
- JSON.parse()和JSON.stringify()
操作的对象
var obj = {a: "Hello",b: {a: "world",b: 111,},c: [11, "Jack", "Tom"],
};
1、浅拷贝
1-1、遍历赋值
// 浅拷贝
function simpleCopy(o) {var o_ = {};for (let i in o) {o_[i] = o[i];}return o_;
}var newObj = simpleCopy(obj);
newObj.b.a = "WORLD";
console.log(obj);console.log(newObj);/**
obj 和 newObj都变了:
b: { "a": "WORLD", "b": 111}}
*/
1-2、Object.create()
var newObj = Object.create(obj);
newObj.b.a = "WORLD";console.log(obj);
// b: {a: "WORLD", b: 111}
console.log(newObj);
// __proto__:
// b: {a: "WORLD", b: 111}
2、深拷贝
2-1、遍历赋值
function deepCopy(object, deepObject=null) {let deepObj = deepObject || {};for (let i in object) {if (typeof object[i] === "object") {// 引用类型 [] {} nullif(object[i] === null){deepObj[i] = object[i];} else{deepObj[i] = object[i].constructor === Array ? []: {}// deepObj[i] = object[i].constructor === Array ? []: Object.create(null);deepCopy(object[i], deepObj[i])}} else{// 简单数据类型deepObj[i] = object[i];}}return deepObj;
}var newObj = deepCopy(obj);
newObj.b.a = "WORLD";console.log(obj);
// b: {a: "world", b: 111}
console.log(newObj);
// b: {a: "WORLD", b: 111}
2-2 JSON
function deepCopy(o) {return JSON.parse(JSON.stringify(o));
}var newObj = deepCopy(obj);
newObj.b.a = "WORLD";console.log(obj);
// b: {a: "world", b: 111}
console.log(newObj);
// b: {a: "WORLD", b: 111}