JS 浅拷贝与深拷贝
2018-01-15 本文已影响0人
麻辣小面瘫
1.浅拷贝(引用类型的复制都是浅拷贝)
var arr1 = [1,2,3,4];
arr2 = arr1;
arr2.push(5);
console.log(arr1);//[1,2,3,4,5]
2.对象的浅拷贝
function copy(obj){
var tempObj = {};
for(var i in obj){
tempObj[i] = obj[i]; //属性复制
}
return tempObj
}
var Person = {
name:'person',
skills:['g','s','m']
}
var newPerson = copy(Person);
console.log(Person.skills ) ;//['g','s','m'];
newPerson.skills.push('b');
console.log(Person.skills); // ['g','s','m','b']; 浅拷贝,只是拷贝了指向引用类型的地址
console.log(newPerson .skills); // ['g','s','m','b'];
2.对象的深拷贝(在浅拷贝的基础上递归调用)
function deepCopy(obj, newObj) {
var tempObj= newObj || {};
for (var i in obj) {
if (typeof obj[i] === 'object') {
tempObj[i] = (obj[i].constructor === Array) ? [] : {};
deepCopy(obj[i], tempObj[i]);
} else {
tempObj[i] = obj[i];
}
}
return tempObj;
};
var Person = {
name:'person',
skills:['g','s','m']
}
var newPerson = deepCopy(Person);
console.log(Person.skills ) ;//['g','s','m'];
newPerson.skills.push('b');
console.log(Person.skills); // ['g','s','m'];
console.log(newPerson .skills); // ['g','s','m','b'];