js
对象为什么要深度拷贝,不深度拷贝有什么影响?
举个例子
var content = {
name: "zmtssdy",
age: 25
}
var newContent = content;
newContent.sex = "male";
console.log(content); //{name:"zmtssdy",age:25,sex:"男"}
将对象通过 “ = ”
复制给另一个对象时,只是相对于给该变量起别名,对别名对象操作的时候也会影响到原对象上,所以通过newContent.sex
给对象content
添加属性可以实现。然而,更多的时候我们希望newContent
和content
对象是独立的,那么就需要生成一个原对象的副本,请看下面的例子:
var cloneObj = function (obj) {
var str, newobj = obj.constructor === Array ? [] : {};
if (typeof obj !== 'object') {
return;
} else if (window.JSON) {
str = JSON.stringify(obj), //序列化对象
newobj = JSON.parse(str); //还原
} else {
for (var i in obj) {
newobj[i] = typeof obj[i] === 'object' ? cloneObj(obj[i]) : obj[i];
}
}
return newobj;
};
//测试
var content = {
name: "zmtssdy",
age: 25,
sex: "男"
};
//执行深度克隆
var newContent = cloneObj(content);
delete newContent.sex;
console.log(newContent); //{name:"zmtssdy",age:25}
console.log(content); //{name:"zmtssdy",age:25,sex:"男"}
如果觉得对你有帮助,留下个赞吧!
网友评论