myCloneDeep.ts 1.45 KB
/**
 * 对象深拷贝
 * @param data - 要拷贝的对象
 **/
export const objCloneDeep = function (data: any) {
  const newObj: any = {};
  for (const key in data) {
    const item = data[key];
    const typeofs = Object.prototype.toString.call(item);
    // console.log(typeofs, item);

    // 如果是对象
    if (typeofs === '[object Object]') {
      newObj[key] = objCloneDeep(item);
    }
    // 如果是数组
    else if (typeofs === '[object Array]') {
      newObj[key] = arrCloneDeep(item);
    } else {
      newObj[key] = item;
    }
  }
  return newObj;
};

/**
 * 数组深拷贝
 * @param data - 要拷贝的数组
 **/
export const arrCloneDeep = function (data: any[]) {
  const newArr: any = [];

  for (const item of data) {
    const typeofs = Object.prototype.toString.call(item);
    // 如果是对象
    if (typeofs === '[object Object]') {
      newArr.push(objCloneDeep(item));
    }
    // 如果是数组
    else if (typeofs === '[object Array]') {
      newArr.push(arrCloneDeep(item));
    } else {
      newArr.push(item);
    }
  }

  return newArr;
};

/**
 * 深拷贝
 * @param data - 要拷贝的data
 **/
export const myCloneDeep = function (data: any) {
  const typeofs = Object.prototype.toString.call(data);
  // 如果是对象
  if (typeofs === '[object Object]') {
    return objCloneDeep(data);
  }
  // 如果是数组
  else if (typeofs === '[object Array]') {
    return arrCloneDeep(data);
  } else {
    return data;
  }
};