js 浅与深拷贝

 1、浅拷贝

let obj1 = {
  a: 1,
  b: 2
}
let obj2 = obj1
obj2.b = 3
console.log(obj1)  // { a: 1, b: 3 }
console.log(obj1 === obj2) //true

 

 2、深拷贝

function deepCopy(obj) {
   if(typeof obj === "object") {
       if(obj.constructor === Array) {
           var newArr = []
           for(var i = 0; i < obj.length; i++) newArr.push(obj[i])
           return newArr
       } else {
           var newObj = {}
           for(var key in obj) {
               newObj[key] = this.deepCopy(obj[key])
           }
           return newObj
       }
   } else {
       return obj
   }
}//理解版

 

let obj1 = {
  a: '1',
  b: '2',
  c: {
    d: '3'
  },
  d: function aa () {}
}
function deepCopy (obj) { //简化后
  let temp = obj.constructor === Array ? [] : {}
  for (let val in obj) {
    temp[val] = typeof obj[val] == 'object' ? deepCopy(obj[val]) : obj[val]
  }
  return temp
}
console.log(deepCopy(obj1)) //{ a: '1', b: '2', c: { d: '3' }, d: [Function: aa] }

 

posted @ 2018-01-03 18:29  浮生如梦似离殇  阅读(155)  评论(0编辑  收藏  举报