实现自己的深拷贝
function deepCopy(obj) {
let result = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === "object") {
result[key] = deepCopy(obj[key]);
} else {
result[key] = obj[key];
}
}
}
return result;
}
let array1 = [{ 1: "2" }, { 3: "4" }];
let array2 = deepCopy(array6);
console.log(array1[0] === array2[0]); //output false
Object.assign()和Object.create()
Object.assign(targeObj,…sourceObjs):
可枚举属性的复制,返回根据targeObj
//当source是一层的时候,Object.assign()方法能实现深拷贝
const target = [1,2];
const source = [3,4];
const returnedTarget = Object.assign(target, source)
target[0] = 5
console.log(source);//output: [3,4]
console.log(target);//output: [5,4]
console.log(returnedTarget);//output: [5,4]
//当source有多层时,从第二层开始后面都是浅拷贝了
const target = [1,2];
const source = [3,[5,6]];
const returnedTarget = Object.assign(target, source)
target[1][0] = 7
console.log(source);//output: [3,[7,6]]
console.log(target);//output: [3,[7,6]]
console.log(returnedTarget);//output: [3,[7,6]]
Object.create(propObj[,propertiesObject]):
创建一个新对象,并提供proto,返回这个新对象
//当obj1是一层的时候(obj1可以是数组),Object.create()方法能实现深拷贝
const obj1 = {
a:1,
b:2
};
const obj2 = Object.create(obj1);
obj2.a = 3;
obj2.b = 4;
console.log(obj1.a)//output:1
console.log(obj1.b)//output:2
console.log(obj2.a)//output:3
console.log(obj2.b)//output:4
//当obj1有多层时(obj1可以是数组),从第二层开始后面都是浅拷贝了
const obj1 = {
a:{x:'x'},
b:2
};
const obj2 = Object.create(obj1);
obj2.a.x = 'hasBeenChanged' ;
obj2.b = 4;
console.log(obj1.a.x)//output:hasBeenChanged
console.log(obj1.b)//output:2
console.log(obj2.a.x)//output:hasBeenChanged
console.log(obj2.b)//output:4
JSON.stringfy()和JSON.parse()
进行序列化和反序列化能够做到深拷贝
const obj1 = {a:1,b:2,c:{x:8,y:9}}
const obj2 = JSON.parse(JSON.stringify(obj1))
obj2.c.x=10
console.log(obj1)//output: {a:1,b:2,c:{x:8,y:9}}
console.log(obj2)//output:{a:1,b:2,c:{x:10,y:9}}
jQuery的extend方法
$.extend(Boolean,targetObj,sourceObjs),第一个参数默认为false表示浅拷贝,改为true表示深拷贝
const $ =require('jquery')
const obj1 = {
a: 1,
b: { d: { e: 1 } },
c: [1, 2, 3]
};
const obj2 = $.extend(true, {}, obj1);
obj2.b.d.e=4;
console.log(obj1)//output:{a:1,b:{d:{e:1},c:[1,2,3]}
console.log(obj2)//output:{a:1,b:{d:{e:4},c:[1,2,3]}
lodash的cloneDeep方法
_.cloneDeep(sourceObj),返回一个targetObj
const _ = require('lodash');
const obj1 = {
a: 1,
b: { d: { e: 1 } },
c: [1, 2, 3]
};
const obj2 = _.cloneDeep(obj1);
obj2.b.d.e=4;
console.log(obj1)//output:{a:1,b:{d:{e:1},c:[1,2,3]}
console.log(obj2)//output:{a:1,b:{d:{e:4},c:[1,2,3]}