JS手写代码实现深拷贝

发布时间 2023-08-28 22:10:16作者: Trkly
/**
 * 深拷贝
 */

const obj1 = {
    age: 20,
    name: 'xxx',
    address: {
        city: 'beijing'
    },
    arr:['a', 'b', 'c']
}
const obj2 = obj1
obj2.address.city = 'shanghai'
console.log(obj1.address.city)

const obj3 = deepClone(obj1)
obj3.address.city = 'weihai'
console.log(obj1.address.city)
/**
 * 深拷贝 
 * @param {Object} obj 要拷贝的对象
 */
function deepClone(obj = {}) {
    if(typeof onj !== 'object' || obj == null){
        // obj是null,或者不是对象和数组,直接返回
        return obj
    }
    // 初始化返回结果
    /**
     * instanceof与typeof的区别
     * [1]typeof:主要用来判断基础数据类型,比如:Number、String 等等。
     * [2]instanceof:主要用来判断对象数据类型
     * [3]typeof 直接返回数据类型,而 instanceof 重在判断,它返回布尔值。
     */
    // 判断对象是否是数组
    if(obj instanceof Array) {
        result = []
    } else {  // 不是数组的话就是对象
        result = {}
    }
    for (let key in obj){
        // 保证key不是原型的属性
        if (obj.hasOwnProperty(key)) {
            // 递归调用!!!
            result[key] =deepClone(obj[key])
        }
    }
    // 返回结果
    return result
}