728x90
반응형
JAVASCRIPT
얕은복사와 깊은복사
🔎 기본 데이터 타입
javascript의 데이터형은 기본 데이터 타입과 참조형 데이터 타입으로 구분된다. 기본 데이터 타입은 아래와 같이 데이터를 복사하게 된다.
const a = 1
const b = a
b = 2
console.log(a) // 1
console.log(b) // 2
const c = 1
const d = c
c = 2
console.log(c) // 2
console.log(d) // 1
🔎 얕은 복사
참조형 데이터 타입 (Array, Object)의 경우 기본형과 동일하게 데이터를 복사하게 되면 얕은 복사(참조 주소 공유)가 되어 다음과 같이 동작한다.
const arr1 = ['a', 'b', 'c', 'd']
const arr2 = arr1
arr2[4] = 'e'
console.log(arr1) // ['a', 'b', 'c', 'd', 'e']
console.log(arr2) // ['a', 'b', 'c', 'd', 'e']
const arr3 = ['a', 'b', 'c', 'd']
const arr4 = arr3
arr3[4] = 'e'
console.log(arr3) // ['a', 'b', 'c', 'd', 'e']
console.log(arr4) // ['a', 'b', 'c', 'd', 'e']
이는 우리가 흔히 예상하는 결과는 아니다. arr1와 arr4는 ['a', 'b', 'c', 'd'] 로 그대로 남아있길 예상하지만 얕은 복사의 경우는 배열(객체)데이터의 참조 주소만 공유될 뿐 참조 공간이 복사 되는 것은 아니다. 참조 공간까지 복사하기 위해서는 깊은 복사를 해야한다.
🔎 깊은 복사 (1차원)
const arr1 = ['a', 'b', 'c', 'd']
const arr2 = arrA.slice()
// slice(), concat(), spread 연산자, Array.from()
arr1[4] = 'e'
console.log(arr1) // ['a', 'b', 'c', 'd', 'e']
console.log(arr2) // ['a', 'b', 'c', 'd']
const obj1 = {
id: 'id'
}
const obj2 = Object.assign({}, obj1)
// Object.assign(), spread 연산자
obj1.name = 'name'
console.log(arr1) // { id: 'id', name: 'name' }
console.log(arr2) // { id: 'id' }
1차원 배열(객체)의 경우 여러 메서드를 통해 깊은 복사가 가능하다. 하지만 2차원 배열(객체)의 경우에는 해당 메서드를 통해서 복사를 하더라도 얕은 복사가 된다.
🔎 얕은 복사 (2차원)
const arr1 = ['a', 'b', [ 'c', 'd' ]]
const arr2 = arrA.slice()
// slice(), concat(), spread 연산자, Array.from()
arr1[1] = 'x'
arr1[2][0] = 'y'
console.log(arr1) // ['x', 'b', [ 'y', 'd']]
console.log(arr2) // ['a', 'b', [ 'y', 'd']]
const obj1 = {
id: 'id'
name: {
first: 'name'
last: 'kim'
}
}
const obj2 = Object.assign({}, obj1)
// Object.assign(), spread 연산자
obj1.id = 'ID'
obj1.name.first = 'NAME'
console.log(arr1) // { id: 'ID', name: { first: 'NAME', last: 'kim' } }
console.log(arr2) // { id: 'id', name: { first: 'NAME', last: 'kim' } }
2차원 배열(객체)까지 더 나아가 다차원 배열(객체)까지 깊은 복사를 위해서는 다른 방법이 필요하다. 많이 사용하는 방법으로는 재귀함수를 통해 모든 깊이를 깊은 복사하는 방법과 JSON을 사용하는 방법이 있다. 그 중 JSON을 활용한 방법에 대해서 알아보자.
🔎 깊은 복사 (JSON)
const arr1 = ['a', 'b', [ 'c', 'd' ]]
const arr2 = JSON.parse(JSON.stringify(arr1))
arr1[1] = 'x'
arr1[2][0] = 'y'
console.log(arr1) // ['x', 'b', [ 'y', 'd']]
console.log(arr2) // ['a', 'b', [ 'c', 'd']]
const obj1 = {
id: 'id'
name: {
first: 'name'
last: 'kim'
}
}
const obj2 = JSON.parse(JSON.stringify(obj1))
obj1.id = 'ID'
obj1.name.first = 'NAME'
console.log(arr1) // { id: 'ID', name: { first: 'NAME', last: 'kim' } }
console.log(arr2) // { id: 'id', name: { first: 'name', last: 'kim' } }
JSON을 활용하여 깊은 복사를 해보았는데 위에 예시에는 없지만 몇가지 데이터 타입에 대해서는 복사되지 않거나 데이터 타입이 달라지는 문제점이 있다. (undefined, date객체 등...)
728x90
반응형