深克隆

298 阅读1分钟
function deepClone(obj) {
    if (obj === null) return null;
    if (typeof obj !== 'object') return obj;
    if (obj instanceof Date) return new Date(obj);
    if (obj instanceof RegExp) return new RegExp(obj);
    const cloneObj = new obj.constructor();  
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {   
            cloneObj[key] = deepClone(obj[key])
        }
    }
    return cloneObj;
}