??js深度拷貝

方法1 定義方法clone

function clone(obj) {
  let copy;
  if (obj instanceof Array) {
    copy = [];
    let i = obj.length;
    while (i--) {
      copy[i] = clone(obj[i]);
    }
    return copy;
  } else if (obj instanceof Object) {
    copy = {};
    for (let k in obj) {
      copy[k] = clone(obj[k]);
    }
    return copy;
  } else {
    return obj;
  }
}

方法1缺點(diǎn):無法拷貝函數(shù)

方法2 使用 JSON.stringify 和 JSON.parse 方法

var arr = ['old', 1, true, ['old1', 'old2'], {old: 1}]
var new_arr = JSON.parse( JSON.stringify(arr));
console.log(new_arr);   //  [ 'old', 1, true, [ 'old1', 'old2' ], { old: 1 } ]

方法2缺點(diǎn):同樣無法拷貝函數(shù)

方法3 定義deepClone函數(shù)

function deepClone(source) {
  // 遞歸終止條件
  if (!source || typeof source !== 'object') {
    return source;
  }
  var targetObj = source instanceof Array ? [] : {};
  for (var key in source) {
    // 該方法會(huì)忽略掉那些從原型鏈上繼承到的屬性。
    if (source.hasOwnProperty(key)){
    // 避免死循環(huán)對(duì)象屬性
      if(source[key] === source){
        console.warn(new Error('circular object'))
      }else if (source[key] && typeof source[key] === 'object') {  //數(shù)組 typeof的結(jié)果也是object
        targetObj[key] = deepClone(source[key]);
      } else {
        targetObj[key] = source[key];
      }
    }
  }
  return targetObj;
}
var object1 = {'year':12, arr: [1, 2, 3], obj: {key: 'value' }, func: function(){return 1;}};
var object2 = [1,[2,[3,4,[5,6]]]]
var newObj= deepClone(object1);
var newObj2 = deepClone(object2)
console.log(newObj)  // { year: 12,arr: [ 1, 2, 3 ],obj: { key: 'value' }, func: [Function: func] }
console.log(newObj2) // [ 1, [ 2, [ 3, 4, [Array] ] ] ]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • js 數(shù)組的深度拷貝 的四種實(shí)現(xiàn)方法 首先聲明本人資質(zhì)尚淺,本文只用于個(gè)人總結(jié)。如有錯(cuò)誤,歡迎指正、共同提高。 v...
    yichen_china閱讀 405評(píng)論 0 0
  • 深拷貝(deepClone) 對(duì)于一個(gè)引用類型,如果直接將它賦值給另一個(gè)變量,由于這兩個(gè)引用指向同一個(gè)地址,這時(shí)改...
    三月孫記風(fēng)閱讀 353評(píng)論 2 0
  • 實(shí)現(xiàn)1: 由于JSON并不是支持所有js數(shù)據(jù)類型(如:Date,Function,Error,RegExp等都不支...
    stanf1l閱讀 1,713評(píng)論 0 0
  • 寫在前面 各類技術(shù)論壇關(guān)于深拷貝的博客有很多,有些寫的也比我好,那為什么我還要堅(jiān)持寫這篇博客呢,之前看到的一篇博客...
    心_c2a2閱讀 21,494評(píng)論 3 18
  • 函數(shù)和對(duì)象 1、函數(shù) 1.1 函數(shù)概述 函數(shù)對(duì)于任何一門語言來說都是核心的概念。通過函數(shù)可以封裝任意多條語句,而且...
    道無虛閱讀 4,926評(píng)論 0 5

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