引用类型深拷贝

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Zckguiying/article/details/86522417
// 递归实现引用类型数据的拷贝
function deepCopy(oldObj, newObj){
  var newObj = newObj || {}
	for(let i in oldObj){
	  if(typeof oldObj[i] === 'object'){
		if (oldObj[i].constructor === Array) {
		  newObj[i] = []
		}
		if (oldObj[i].constructor === Object) {
		  newObj[i] = {}
		}
		deepCopy(oldObj[i], newObj[i])
	  } else {
		newObj[i] = oldObj[i]
	  }
	}
	return newObj
 }


var person = {
  name: 'justicky',
  age: 224,
  skill: ['react', 'vue'],
  work: {
	use: 'computer',
	tranform: 'subway'
  }
}

var newPerson = {}
newPerson = deepCopy(person)
console.log('拷贝前' + JSON.stringify(person))
console.log('拷贝后' + JSON.stringify(newPerson))

猜你喜欢

转载自blog.csdn.net/Zckguiying/article/details/86522417