1. 程式人生 > 其它 >JS-深拷貝

JS-深拷貝

JS-深拷貝

/**
 * 深拷貝
 */

const obj1 = {
    age: 20,
    name: 'xxx',
    address: {
        city: 'beijing'
    },
    arr: ['a', 'b', 'c']
}

const obj2 = deepClone(obj1)
obj2.address.city = 'shanghai'
obj2.arr[0] = 'a1'
console.log(obj1.address.city) // beijing
console.log(obj1.arr[0]) //a 


/**
 * 深拷貝的實現
 
*/ function deepClone(item) { // 判斷是否為需要遍歷的物件 if (typeof item !== 'object' || item == null) { // 直接返回 return item } // 初始化一個返回結果 let result; // 判斷是陣列還是物件 初始化result if (item instanceof Array) { result = [] } else { result = {} } // 遞迴 注意是要迴圈物件的所有可列舉屬性
// 然後再使用hasOwnProperty來忽略掉不是自身的繼承的屬性 for (let key in item) { if (item.hasOwnProperty(key)) { // 遞迴呼叫! result[key] = deepClone(item[key]); } } return result }
點:
  • 遞迴
  • hasOwnProperty
  • for...in迴圈物件的所有列舉屬性,然後再使用hasOwnProperty()方法來忽略繼承屬性。(常用)