likes
comments
collection
share

js手写deepClone深拷贝

作者站长头像
站长
· 阅读数 25

背景

实际开发中,处理数据经常会使用到数据拷贝。其实使用JSON.stringify()与JSON.parse()来实现深拷贝是很不错的选择。

但是当拷贝的数据为undefined,function(){}等时拷贝会为空,这时就需要采用递归拷贝。

使用JSON实现拷贝时,注意拷贝数据,看是否适合使用。

以下是手写简单深拷贝

代码

/**
 * @param obj
 * @description 深拷贝
 */
export const deepClone = (obj: any) => {
  // 判断是否需要递归
  if (typeof obj !== 'object' || obj == null) {
    return obj;
  }
  let result: any;
  if (obj instanceof Array) {
    result = [];
  } else {
    result = {};
  }
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      result[key] = deepClone(obj[key]);
    }
  }
  return result;
};

export default deepClone;