deepCompare和deepClone 深度复制

186 阅读1分钟
// 深度复制
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;
}
function deepCompare(a, b) {
  if (
    a === null ||
    typeof a !== 'object' ||
    b === null ||
    typeof b !== '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]));
}