1. 程式人生 > >js實現深拷貝

js實現深拷貝

font all != 賦值 class function style pro return

  js的數據類型分為基本數據類型和引用數據類型。基本數據類型是直接賦值,引用數據類型分為淺拷貝和深拷貝。淺拷貝是復制對象的指針,深拷貝是復制對象所有屬性再內存中獨立存在。

  淺拷貝如下:

var obj = {a: ‘test‘, b: {c: 0}}
var obj1 = obj
var obj2 = shallowCopy(obj);
function shallowCopy(src) {
    var dst = {};
     for (var prop in src) {
         if (src.hasOwnProperty(prop)) {
             dst[prop] = src[prop];
          }
      }
     return dst;
}

var obj3 = Object.assign({}, obj)

obj.a = ‘arr‘
obj.b.c = 1

console.log(obj) // {a: ‘arr‘, b: {c: 1}}
console.log(obj1) // {a: ‘arr‘, b: {c: 1}}
console.log(obj2) // {a: ‘test‘, b: {c: 1}}
console.log(obj3) // {a: ‘test‘, b: {c: 1}}

  深拷貝實現如下:

function extend (source) {
  var target
  if (typeof source === ‘object‘) {
    target = Array.isArray(source) ? [] : {}
    for (var key in source) {
      if (source.hasOwnProperty(key)) {
        if (typeof source[key] !== ‘object‘) {
          target[key] = source[key]
        } else {
          target[key] = extend(source[key])
        }
      }
    }
  } else {
    target = source
  }
  return target
}

var obj1 = {a: {b: 0}}
var cpObj1 = extend(obj1)
obj1.a.b = 1
console.log(cpObj1) // {a: {b: 0}}

var obj2 = [[0]]
var cpObj2 = extend(obj2) 
obj2[0][0] = 1
console.log(cpObj2) // [[0]]

  

js實現深拷貝