JavaScript 的 deepCopy 和 shallowCopy 之間的區別


淺複製和深複製與語言無關。淺複製儘可能少地複製。一個集合的淺複製是集合結構的副本,而不是元素的副本。使用淺複製,兩個集合現在共享各個元素。

示例

let innerObj = {
   a: 'b',
   c: 'd'
}
let obj = {
   x: "test",
   y: innerObj
}
// Create a shallow copy.
let copyObj = Object.assign({}, obj);
// Both copyObj and obj's prop y now refers to the same innerObj. Any changes to this will be reflected.
innerObj.a = "test"
console.log(obj)
console.log(copyObj)

輸出

{ x: 'test', y: { a: 'test', c: 'd' } } 
{ x: 'test', y: { a: 'test', c: 'd' } } 

請注意,淺複製不會遞迴地建立克隆。它只在頂層進行。

深複製複製所有內容。一個集合的深複製是兩個集合,其中原始集合中的所有元素都被克隆。

示例

let innerObj = {
   a: 'b',
   c: 'd'
}
let obj = {
   x: "test",
   y: innerObj
}
// Create a deep copy.
let copyObj = JSON.parse(JSON.stringify(obj))
// Both copyObj and obj's prop y now refers to the same innerObj. Any changes to this will be reflected.
innerObj.a = "test"
console.log(obj)
console.log(copyObj)

輸出

{ x: 'test', y: { a: 'test', c: 'd' } } 
{ x: 'test', y: { a: 'b', c: 'd' } } 

更新日期: 2019-09-16

183 次瀏覽

開啟你的 事業

完成該課程,獲得認證

開始
廣告