unliar / unliar.github.io

一个已经不再使用的静态博客,新的博客在后边。
https://happysooner.com
0 stars 0 forks source link

js实现深拷贝deepClone #35

Open unliar opened 3 years ago

unliar commented 3 years ago
// 判断是否数组
const isArray = (src) => Object.prototype.toString.call(src).includes("Array");
// 判断是否是对象
const isObject = (src) =>
  Object.prototype.toString.call(src).includes("Object");
// 具体实现
const DeepClone = (src) => {
  let res = null;
  // 非数组 或者 对象
  if (!isArray(src) && !isObject(src)) {
    res = src;
  }
  // 数组
  if (isArray(src)) {
    res = [];
    src.forEach((item, index) => {
      res[index] = DeepClone(item);
    });
  }
  // 对象
  if (isObject(src)) {
    res = {};
    for (const key in src) {
      if (Object.hasOwnProperty.call(src, key)) {
        res[key] = DeepClone(src[key]);
      }
    }
  }
  return res;
};
console.log(Object.prototype.toString.call(DeepClone))