myCloneDeep.ts 1.45 KB
Newer Older
hucy's avatar
hucy committed
1 2 3 4 5 6 7 8 9
/**
 * 对象深拷贝
 * @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);
hcyhuchaoyue's avatar
hcyhuchaoyue committed
10
    // console.log(typeofs, item);
hucy's avatar
hucy committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

    // 如果是对象
    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;
  }
};