一、数组的深拷贝
var arr = ["one", "two", "three"];
var arrCopy = arr;
arrCopy[1] = "test";
console.log(arr); //["one", "test", "three"]
console.log(arrCopy); //["one", "test", "three"]
1.如果直接将一个数组赋值给另一个数组,那么改变其中一个,另一个也会改变,这是数组的浅拷贝。
2.解决方案:利用数组的slice和concat方法,这两个方法都在不会改变原数组的基础上而产生一个新数组。
var arr = ["one", "two", "three"];
var arrCopy = arr.slcie(0); // arrCopy = arr.concat();
arrCopy[1] = "test";
console.log(arr); //["one", "two", "three"]
console.log(arrCopy); //["one", "test", "three"]
二、对象的深拷贝
var json = {name: "aaa", age: 12};
var jsonCopy = json;
jsonCopy.name = "bbb";
console.log(json); // {name: "bbb", age: 12}
console.log(jsonCopy); // {name: "bbb", age: 12}
1.同理,对象这样直接赋值也是浅拷贝。
2.解决方案:就是把对象的属性遍历一遍,赋给一个新的对象。
var json = {name: "aaa", age: 12};
var jsonCopy = new Object();
jsonCopy.name = json.name;
jsonCopy.age = json.age;
jsonCopy.name = "bbb";
console.log(json); // {name: "aaa", age: 12}
console.log(jsonCopy); // {name: "bbb", age: 12}
var deepCopy = function(source) {
var result={};
for (var key in source) {
result[key] = typeof source[key]===‘object‘? deepCopy(source[key]): source[key];
}
return result;
}