关于javascript:js深拷贝deepClone

11次阅读

共计 481 个字符,预计需要花费 2 分钟才能阅读完成。

function deepClone(obj = {}) {
    // obj 是 null 或 undefined(留神这里应用的 == 不是 ===)或者不是对象和数组,间接返回
    if (typeof obj !== 'object' || obj == null) {return obj}
    // 初始化返回后果
    let result
    if (obj instanceof Array) {result = []
    } else {result = {}
    }
    for(let key in obj) {
        // 保障 key 不是原型的属性
        if (obj.hasOwnProperty(key)) {
            // 递归
            result[key] = deepClone(obj[key])
        }
    }
    // 返回后果
    return result
}

// 测试
const obj1 = {
    age: 20,
    name: '张三',
    addresss: {city: 'beijing'},
    arr: ['a', 'b', 'c']
}

const obj2 = deepClone(obj1)
obj2.name = '李四'
obj2.addresss.city = 'hefei'
obj1.arr[0] = 100
console.log(obj1, obj2)

正文完
 0