js深度Clone

参考来源:https://www.jianshu.com/p/74201ed5184d

解决已知问题。 

Object.deepClone=(obj)=>{
    let newObject;
    if(obj === null) {  
          return null;
    } 
    else if (!(obj instanceof Object)) { 
        return obj;
    } 
    else if (obj instanceof Date) {
         return new Date(obj);
    }
    else if (obj instanceof Function) { 
        return Object.assign(obj);
    }
    else if (obj instanceof RegExp) {
        return new RegExp(obj);
    }
    else if (obj instanceof Array){
        newObject = [];
        for(item of obj) {
            newObject.push(Object.deepClone(item));
        }
    } 
     else {
        newObject = Object.assign(Object.create(Object.getPrototypeOf(obj)),obj);
        for(let key of Object.keys(obj)) {
            
            if(newObject[key] != obj)
            {
                newObject[key] = Object.deepClone(obj[key]);
            }else
            {
                newObject[key] = newObject;
            }
        }
    }
     return newObject;
 }

猜你喜欢

转载自blog.csdn.net/l100142548/article/details/89453147