deepClone deepCompare

一、深度复制

// 深度复制
function deepClone(datas) {
  if (typeof datas !== 'object' || datas === null) return datas;
  const newData = new datas.constructor();
  for (const key in datas) {
    if (Object.hasOwnProperty.call(datas, key)) {
      newData[key] = deepClone(datas[key]);
    }
  }
  return newData;
}

const datas = {
  family: {
    father: 'baba',
    mother: 'mama',
    children: ['brother', 'sister'],
  },
  mine: {
    name: 'shangyy',
    hobby: ['basketball', 'football'],
  },
};

const cloneDatas = deepClone(datas);
console.log(cloneDatas);


二、深度比较

// 深度比较

function deepCompare(a, b) {
  if (a === null || typeof a !== 'object' || a === null || typeof a !== 'object') {
    return a === b;
  }
  const propsA = Object.getOwnPropertyDescriptors(a);
  const propsB = Object.getOwnPropertyDescriptors(b);
  if (Object.keys(propsA).length !== Object.keys(propsB).length) return false;
  return Object.keys(propsA).every(key => deepCompare(a[key], b[key]));
}

const dataA = {
  name: 'shangyy',
  age: 18,
};
const dataB = {
  name: 'shangy',
  age: 18,
};

const result = deepCompare(dataA, dataB);
console.log(result);

 

posted @ 2019-06-03 14:16  shangyueyue  阅读(206)  评论(0编辑  收藏  举报