js 深拷貝

ES6 可否使用Object.assign實現深淺拷貝?

答案:當對象中只有一級屬性,沒有二級屬性的時候,此方法爲深拷貝,可是對象中有對象的時候,此方法,在二級屬性之後就是淺拷貝。數組

看例子:
1 普通變量數據結構

let obj={name:"zhangsan",colors:["red", "green", "blue"]};  
let obj2=Object.assign({},obj);  
obj2.name='wang';  
console.log(obj2);//name wang colors:["red", "green", "blue"]  
console.log(obj);//name zhangsan colors:["red", "green", "blue"]

結論:普通變量拷貝能夠使用Object.assigncode

2 引用變量對象

let obj={name:"zhangsan",colors:["red", "green", "blue"]};  
let obj2=Object.assign({},obj);  
obj2.colors[0]='orange';  
console.log(obj2);//name zhangsan colors:["orange", "green", "blue"]  
console.log(obj);//name zhangsan colors:["orange", "green", "blue"]

結論:Object.assign對於含有引用類型值的對象沒法深拷貝。遞歸

3 數組get

3.1 普通數組string

let colors = ['red','green','blue'];  
let colors2 = Object.assign([],colors);  
colors2[0] = "orange";  
console.log(colors2);//['orange','green','blue']  
console.log(colors);//['red','green','blue']

結論:普通數組拷貝能夠使用Object.assignio

3.2 含有引用類型的值的數組console

let colors=['red','green','blue',['football','basketball','volleyball']];  
let colors2=Object.assign([],colors);  
colors2[3][0]="ping-pang";  
console.log(colors2);//['red','green','blue',['ping-pang','basketball','volleyball']]  
console.log(colors);//['red','green','blue',['ping-pang','basketball','volleyball']]

結論:和上面同樣,若是一維數組裏面有引用類型的值,則沒法深拷貝。function

如何實現深拷貝?

1 數據結構中不包含引用類型

使用Object.assign(),{...obj}等效

2 數據結構中包含引用類型,符合JSON規則(不包含functon)

直接使用:JSON.parse(JSON.stringify({xxx:'xxx})),簡單粗暴~~~~ .

3 數據結構中既有引用類型,又有function

1 經過jQuery的extend方法實現深拷貝,可是估計較少人使用jQuery了
2 lodash.cloneDeep()實現深拷貝

let obj1 = {
    a: 1,
    b: { f: { g: 1 } },
    c: [1, 2, 3]
};
let obj2 = _.cloneDeep(obj1);

3 使用遞歸的方式實現深拷貝

function _deepClone(source) {
  let target;
  if (typeof source === 'object') {
    target = Array.isArray(source) ? [] : {}
    for (let key in source) {
      if (source.hasOwnProperty(key)) {
        if (typeof source[key] !== 'object') {
          target[key] = source[key]
        } else {
          target[key] = _deepClone(source[key])
        }
      }
    }
  } else {
    target = source
  }
  return target
}
相關文章
相關標籤/搜索