原始碼:
支援拷貝string、number、boolean、null、undefined、object(function、array、regexp、date、環)
class deepcloner
clone(source) else else if (source instanceof function)
} else if (source instanceof date) else if (source instanceof regexp) else
this.cache.push([source, dist]);// 環的情況
for (let key in source)
return dist}}
return source
}findcache(source) )
it('測試深拷貝基礎型別', ()=>)
})describe('物件', ()=>}
const a2 = new deepcloner().clone(a)
assert(a !== a2)
assert(a.name === a2.name)
assert(a.child !== a2.child)
assert(a.child.name === a2.child.name)
});it('能夠複製陣列物件', ()=> );
it('能夠複製函式', ()=>
a.xx = }
const a2 = new deepcloner().clone(a)
assert(a.xx !== a2.xx)
assert(a.xx.yy !== a2.xx.yy)
assert(a.xx.yy.zz === a2.xx.yy.zz)
assert(a !== a2)
assert(a(1,2) === a2(1,2))
});it('環也能複製', ()=>
a.self = a
const a2 = new deepcloner().clone(a)
assert(a !== a2)
assert(a.name === a2.name)
assert(a.self !== a2.self)
});it('能夠複製date', ()=>
a.self = a
const a2 = new deepcloner().clone(a)
assert(a !== a2)
assert(a.name === a2.name)
assert(a.self !== a2.self)
});it('能夠複製regexp', ()=>
const a2 = new deepcloner().clone(a)
assert(a.source === a2.source);
assert(a.flags === a2.flags);
assert(a !== a2);
assert(a.obj !== a2.obj);
assert(a.obj.name === a2.obj.name);
});it('能夠複製日期', ()=>
const a2 = new deepcloner().clone(a)
assert(a.source === a2.source);
assert(a.flags === a2.flags);
assert(a !== a2);
assert(a.obj !== a2.obj);
assert(a.obj.name === a2.obj.name);
});})
js深轉殖深拷貝
不足之處是不能拷貝函式,但是基本夠用 const deepcopy obj json parse json stringify obj 如果涉及拷貝函式 簡單一點 function copy object for const k,v of object.entries object return o...
js淺拷貝深拷貝
js淺拷貝深拷貝 對於想要複製的物件,如果物件裡面對應的值都是基本資料型別的,可以直接複製 也就是通過淺拷貝複製。如果對應的值有物件那麼淺拷貝是行不通的。會造成資料汙染。下面介紹淺拷貝與深拷貝實現方法。1.淺拷貝 let tem let copy for let key in tem 2.通過obj...
淺拷貝,深拷貝 js
堆和棧 基本型別 存放在棧中的簡單資料段,資料大小確定,記憶體空間大小可以分配。6種基本資料型別 undefined null boolean number和string,es6新增屬性symbol.他們是直接按值存放的,所以可以直接訪問。引用型別 存放在堆記憶體中的物件,變數實際儲存的是乙個指標,...