JS深拷貝

JS深拷貝的方法

  1. JSON.parse(JSON.stringify(a))
    簡單深拷貝的方法
    缺點:

    1. 不支持undefined、Date、正則、函數(shù)
    2. 不支持引用
      例:
    var b = {
      a:2,
      b:'b'
    }
    var a = {
      a:1,
      b:b
    }
    var c = JSON.parse(JSON.stringify(a)) 
    

    上面的例子中a.b引用了b,這樣就不能用JSON.parer()這種方法進行深拷貝

  2. 遞歸

要點:
- 判斷類型
- 不拷貝原型上的屬性方法
- 處理環(huán)(循環(huán)引用)

const deepclone = (a, cache) => {
  if (!cache) {
    cache = new Map();
  }
  // a是對象
  if (a instanceof Object) {
    //處理循環(huán)引用的情況
    if (cache.get(a)) {
      return cache.get(a);
    }
    let result;
    //a是函數(shù)
    if (a instanceof Function) {
      //a是普通函數(shù)
      if (a.prototype) {
        result = function () {
          return a.apply(this, arguments);
        };
      } else {
        // 箭頭函數(shù)
        result = (...args) => {
          a.call(undefined, ...args);
        };
      }
    }
    //a是Date
    else if (a instanceof Date) {
      result = new Date(a - 0); //a-0 可以將Date轉(zhuǎn)為對應的時間戳
    }
    //a是Regexp
    else if (a instanceof RegExp) {
      result = new RegExp(a.source, a.flags);
    }
    //a是普通對象
    else {
      result = {};
    }
    cache.set(a, result);
    //拷貝其他屬性
    for (var key in a) {
      //只拷貝自身屬性,原型上的屬性不拷貝
      if (a.hasOwnProperty(key)) {
        result[key] = deepclone(a[key], cache);
      }
    }
    return result;
  } else {
    //a是原始類型 string number boole null undefined Symbol bigint
    return a;
  }
};

const a = {
  number: 1,
  bool: false,
  str: "hi",
  empty1: undefined,
  empty2: null,
  array: [
    { name: "aa", age: 18 },
    { name: "bb", age: 19 },
  ],
  date: new Date(2000, 0, 1, 20, 30, 0),
  regex: /\.(j|t)sx/i,
  obj: { name: "aaa", age: 18 },
  f1: (a, b) => a + b,
  f2: function (a, b) {
    return a + b;
  },
};
a.self = a;
const b = deepclone(a);
console.log(b.self === b); // true
b.self = "hi";
console.log(a.self !== "hi"); //true
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容