JS对象的深拷贝
1、JSON的parse和stringify,缺点是对象中属性值为undefined,函数和symbol的属性会省略。
let obj1 = { name: ‘张三‘, age: undefined, see: function(){ console.log("看"); }, son: { name: ‘张四‘ } } let obj2 = JSON.parse(JSON.stringify(obj1));
2、手写递归方法
function deepClone(target){ if(target === null) return null; if(typeof target !== ‘object‘) return target; const cloneTarget = Array.isArray(target) ? [] : {}; for( let prop in target){ if(target.hasOwnProperty(prop)){ cloneTarget[prop] = deepClone(target[prop]); } } return cloneTarget; }
JS对象的浅拷贝
Object.assgin()