function deepCopy(originData){ const newData = originData.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象 for(let key in originData){ // 遍历目标 if(originData.hasOwnProperty(key)){ if(originData[key] && typeof originData[key] === 'object'){ // 如果值是对象,就递归一下 newData[key] = originData[key].constructor === Array ? [] : {}; newData[key] = deepCopy(originData[key]); }else{ // 如果不是,就直接赋值 newData[key] = originData[key]; } } } return newData; }
试用一下:
const originObj = {a:'a',b:'b',c:[1,2,3],d:{dd:'dd'}}; const cloneObj = deepCopy(originObj); console.log(cloneObj === originObj); // false cloneObj.a = 'A'; cloneObj.c = [4,5,6]; cloneObj.d.dd = 'DD'; console.log(originObj); // {a:'a',b:'b',c:[1,2,3],d:{dd:'dd'}}; console.log(cloneObj); // {a:'A',b:'b',c:[4,5,6],d:{dd:'DD'}};