深拷贝和浅拷贝
浅拷贝
浅拷贝只能拷贝最外面一层
更深级别的对象只能拷贝地址,更改拷贝的新对象时也会改变被拷贝的对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| var obj = { id: 1, name: "andy", msg: { age: 18, }, }; var o = {}; for (var k in obj) { o[k] = obj[k]; } console.log(o);
o.msg.age = 2;
Object.assign(o, obj);
|
深拷贝
这个方法需要传入两个参数,有些繁琐
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| function deepCopy(newObj, oldObj) { for (var key in oldObj) { var item = oldObj[key]; if (item instanceof Array) { newObj[k] = []; deepCopy(newObj[k], item); } else if (item instanceof Object) { newObj[k] = {}; deepCopy(newObj[k], item); } else { newObj[k] = item; } } }
|
还有一种只传一个参数的写法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| function deepClone(obj){ if(obj === null){ return null; } var newObj = obj instanceof Array ? [] : {}; for(var i in obj){ if(typeof obj[i] === "object"){ if(newObj instanceof Array){ newObj.push(deepClone(obj[i])); }else{ newObj[i] = deepClone(obj[i]); } }else{ if(newObj instanceof Array){ newObj.push(obj[i]); }else{ newObj[i] = obj[i]; } } } return newObj; }
|