简单点来说,就是假设B复制了A,当修改A时,看B是否会发生变化,如果B也跟着变了,说明这是浅拷贝,拿人手短,如果B没变,那就是深拷贝,自食其力。(浅拷贝 只拷贝指针,深拷贝就是拷贝他的值,重新生成的对像。就像是浅拷贝就是你的影子,深拷贝是你的克隆人,你没了影子也就没了,但是克隆人还活着。)
浅拷贝例子
let a = [0,1,2,3,4,5],
b = a
a[0] = 1 ;
console.log(a) //[1,1,2,3,4,5]
console.log(b) //[1,1,2,3,4,5]
深拷贝—1.递归复制
function deepClone(obj){
let objClone = Array.isArray(obj)?[]:{};
if(obj && typeof obj==="object"){
for(key in obj){
if(obj.hasOwnProperty(key)){
//判断ojb子元素是否为对象,如果是,递归复制
if(obj[key]&&typeof obj[key] ==="object"){
objClone[key] = deepClone(obj[key]);
}else{
//如果不是,简单复制
objClone[key] = obj[key];
}
}
}
}
return objClone;
}
let a=[1,2,3,4],
b=deepClone(a);
a[0]=2;
console.log(a); //[2,2,3,4,5]
console.log(b); //[1,2,3,4,5]
2.深拷贝–JSON对象的parse和stringify
function deepClone(obj){
let _obj = JSON.stringfy(obj),
objClone = JSON.parse(_obj);
return objClone;
}
let a = [0,1,[2,3],4],
b = deepClone(a);
a[0] = 1 ;
a[2][0] = 1 ;
console.log(a) //[1,1,[1,3],4]
console.log(b) //[0,1,[2,3],4]
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;
};
let testObj = {
name: "weiqiujuan",
sex: "girl",
age: 22,
favorite: "play",
family: {brother: "wei", mother: "haha", father: "heihei"}
}
let testObj2 = deepClone(testObj);
testObj.age = 33
console.log(testObj,testObj2)
4.深拷贝–JQ的extend方法
slice()方法静态浅拷贝