1. 深拷貝和淺拷貝
淺拷貝是都值指向同一塊內存區塊,?而深拷貝則是另外開辟了一塊區域?
// 淺拷貝
const a = {t: 1, p: 'gg'};
const b = a;
b.t = 3;
console.log(a);? // {t: 3, p: 'gg'}
console.log(b);? // {t: 3, p: 'gg'}
//深拷貝
const c = {t: 1, p: 'gg'};
const d = deepCopy(c); // 下面有deepCopy方法
d.t = 3;
console.log(c); // {t: 1, p: 'gg'}
console.log(d); // {t: 3, p: 'gg'}
可以明顯看出,淺拷貝在改變其中一個值時,會導致其他也一起改變,而深拷貝不會。
2. Object.assign() “深層” 拷貝
es6?中有關于深層拷貝的方法Object.assign()?
// Cloning an object
var obj = { a: 1 };
var copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
// Merging objects
var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };
var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1);? // { a: 1, b: 2, c: 3 }, target object itself is changed.
這樣既可以實現clone又可以實現merge(合并)
3. Object.assign()的merge(合并元素)問題:
const defaultOpt = {? title: {? ? ?text: 'hello world',? ?subtext: 'It\'s my world.'? ?} };
const opt = Object.assign({}, defaultOpt, {? title: {? ?subtext: 'Yes, your world.'? }} );
console.log(opt);
// 預期結果 {? title: {? ?text: 'hello world',? subtext: 'Yes, your world.'? ? }}
// 實際結果 {? title: {? ? subtext: 'Yes, your world.'? ? } }
可以看出defaultOpt中的title被整個覆蓋掉了。所以深層拷貝只merge根屬性,子屬性就不做處理了。只能通過先深層拷貝獲取一個內存區域,然后修改內存區域內的值來改變子屬性的值:
const opt = Object.assign({}, defaultOpt);?
opt.title.subtext= 'Yes, your world',
console.log(opt);
// 結果正常? ?{ title: { text: 'hello world',? subtext: 'Yes, your world.' } }
4. 同樣說明Object.assign()它只對頂層屬性做了賦值,并沒有繼續做遞歸之類的操作把所有下一層的屬性做深拷貝。
const defaultOpt = {? title: {? text: 'hello world',? subtext: 'It's my world.' } };
const opt1 = Object.assign({}, defaultOpt);
const opt2 = Object.assign({}, defaultOpt);
opt2.title.subtext = 'Yes, your world.';
console.log('opt1:', opt1);
console.log('opt2:', opt2);
// 結果
opt1: {? title: {? text: 'hello world',? subtext: 'Yes, your world.'? ? } }
opt2: {? title: {? text: 'hello world',? subtext: 'Yes, your world.'? } }
5. 一個可以簡單實現深拷貝的方法:
const obj1 = JSON.parse(JSON.stringify(obj));
思路就是將一個對象轉成json字符串,然后又將字符串轉回對象。
JS deepCopy:
function?clone(obj) {????
????var?c = obj?instanceof?Array ? [] : {};???
?????for?(var?i?in?obj)?if?(obj.hasOwnProperty(i)) {?
???????????var?prop = obj[i];????????????
????????????if?(typeof?prop ==?'object') {
????????????????if?(prop?instanceof?Array) {
????????????????????c[i] = [];
????????????????????for?(var?j = 0; j < prop.length; j++) {
????????????????????????if?(typeof?prop[j] !=?'object') {
????????????????????????????c[i].push(prop[j]);?
???????????????????????}?else?{?
???????????????????????????c[i].push(clone(prop[j]));?
???????????????????????}
????????????????????}?
???????????????}?else?{
????????????????????c[i] = clone(prop);
????????????????}?
???????????}?else?{
????????????????c[i] = prop;
????????????}
? ? ? ?}?
???return?c;
}