js 深拷贝

let obj = {
  age: 12,
  list: [
    {
      name: 'aa'
    },
    {
      name: 'bb'
    }
  ]
}

function cloneDeep(obj) {
  let temp = null;
  if(typeof obj != 'object'){
    temp = obj
  } else {
    if(Array.isArray(obj)){
      temp = []
    }else{
      temp = {}
    }
    for([k, i] of Object.entries(obj)){
      temp[k] = cloneDeep(i)
    }
  }
  return temp
}

let obj2 = cloneDeep(obj)

obj2.list[0].name = 'cc'

console.log(obj);

你可能感兴趣的:(js 深拷贝)