對象的深拷貝和淺拷貝

const obj = {函數

  a: 'hello',spa

  b: {code

    a: 'hello',對象

    b: 'world'blog

  },string

  c: ['good', 'good','study'],it

  d: function() {io

    console.log('hello world')console

  }function

}

對象的淺拷貝

方法一:(for in循環)

function simpleCopy (data) {

  let newObj = {};

  if (data) {

    for (let i in data) {

      newObj[i] = data[i]
    }
    return newObj;
  }

}

const newObj = simpleCopy(obj);

newObj.b.a = 'newObj';

console.log(obj.b.a)         // 返回 {a: 'newObj',b: 'world'}

方法二:

const newObj = new assign({},obj);

以上的兩種方法在拷貝對象的時候,都存在如下的不足:

缺點:當對象的value爲對象時,被拷貝的對象的值發生變化時,原先對象的值也會發生變化

對象的深拷貝

方法一:

function deepCopy (obj) {

  let newObj  = {};

  if (obj) {

    newObj = JSON.parse(JSON.stringify(obj));
  }

  return newObj;

}

缺點: 當對象的value爲函數的時候,這個方法沒法解析

方法二:

function deepCopy(initObj, finalObj) {

  let obj = finalObj || {};

  if (obj) {

    for (let i in initObj) {

      if (initObj[i] === obj) {   // 避免相互引用出現的死循環

        continue;
      }
      if (typeof initObj[i] === 'object') {

        obj[i] = (initObj[i].constructor === Array) ? [] : {};
        arguments.callee(initObj[i], obj[i])
      } else {

        obj[i] = initObj[i]
      }
    }
    return obj;
  }

}

注: 比較理想的方法

相關文章
相關標籤/搜索