js手写一个简易深拷贝函数

36 阅读1分钟

为了加深印象,记录一下:

function deepClone(obj = {}) {
    if (typeof obj !== 'Object' || obj == null) {
        //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 //返回结果
}

涉及知识点:值类型的判断 typeof、instanceof、hasOwnProperty等用法