深浅拷贝

167 阅读1分钟

数组的浅拷贝

  1. 使用 contact
const arrayA = [1,'1',null,undefined]
const arrayB = arrayA.concat()
console.log(arrayB)
  1. 使用slice
const arrayA = [1,'1',null,undefined]
const arrayB = arrayA.slice()
console.log(arrayB)

上面的两种方法利用了 slice 和 concat 会返回一个新数组的特性。

对象的浅拷贝

要想实现对象的浅拷贝只需要遍历就可以了。

const objA = {a:1,b:2,c:3}
const objB = {}
for(let key in objA){
	if ( objA.hasOwnProperty(key) ){
    	objB[key] = objA[key]
    }
}

深拷贝

当数组 / 对象 中还有有对象时,使用浅拷贝会拷贝到对象的引用,造成数据修改的不可控。所以,我们需要使用深拷贝。

  1. 使用JSON的api
const arrA = [ 1, 2, 3, {b:2} ]
const arrB = JSON.parse( JSON.stringify(arrA) )
  1. 使用递归
const deepClone = (obj) => {
  if (typeof obj !== 'object') return;
  const newObj = obj instanceof Array ? [] : {};
  for( let key in obj ){
    if( obj.hasOwnProperty(key) ){
      newObj[key] = typeof obj[key] === 'object' 
      		? deepClone(obj[key]) 
      		: obj[key]
    }
  }
  return newObj
}

const arrA = [1,{b:2}]
const arrB = deepClone(arrA)
console.log(arrB)