JS 深拷贝方法记录

186 阅读1分钟
通过递归调用浅拷贝的方式实现:

deepCopy(obj) {     
    let objArray = Array.isArray(obj) ? [] : {};
     if (obj && typeof obj === "object") {
       for (const key in obj) {
         if (obj.hasOwnProperty(key)) {
           if (obj[key] && typeof obj[key] === "object") {
             objArray[key] = this.deepCopy(obj[key]);
           } else {
             objArray[key] = obj[key];
           }
         }
       }
     }
     return objArray;
   }

也可以用jquery下面的extend工具方法实现:

jQuery.extend([deep], target, object1, [objectN]);

第一个参数设置为true,则jQuery返回一个深层次的副本,递归地复制找到的任何对象。

let obj = {
    childs: ['jake', 'tom'],
    age: 45
}
let newObj = $.extend(true, {}, obj)
newObj.childs[0] = 'jone'
console.log(newObj.childs[0]) //----'Jone'
console.log(obj.childs[0]) //-----'jake'