JS 对象深度拷贝方法 js对象赋值问题(对象赋值影响原对象、对象赋值后原对象值随之变化)
11
解决方法(转换类型法): JSON.parse(JSON.stringify(obj))
解决方法(es6之Object.assign()法):obj2=Object.assign({},obj1)
终极解决方案:
// 对象深度拷贝方法
function deepCopy(obj) {
let copy;
// Handle the 3 simple types, and null or undefined
if (null == obj || "object" != typeof obj) return obj;
// Handle Array
if (obj instanceof Array) {
copy = [];
for (let i = 0, len = obj.length; i < len; i++) {
copy[i] = deepCopy(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
copy = {};
for (let attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = deepCopy(obj[attr]);
}
return copy;
}
}
let a = {
xiaoming: {
yuwen: 89,
shuxue: 99,
yingyu: 100
},
xiaoma: [
'a','b','c'
]
};
let b = a;
let c = Object.assign({}, a);
let d = deepCopy(a);
console.log('@',a,b,c,d);
a.xiaoming.yuwen = 100;
console.log('#',a,b,c,d);