🐾 얕은 복사, 깊은 복사 비교

얕은 복사
얕은 복사는 사본을 만들지 않고 원본을 참조하면서 복사한 척 하는 것 Ex) slice()
slice
- slice 는 배열을 복사하는 기능(string 가능, 객체는 불가능)
- 중첩된 배열인 A를 A’로 복사한 후 A’에 중첩되어있는 배열안에 값을 넣으면 원본인 A에 중첩되아있는 배열안에 영향을 미쳐 값이 들어간다.
- 중첩된 배열이 아닌 배열안에 값을 넣었을 때에는 원본 A에 영향을 받지 않는다
const arr =[1,2,[3,4]]
const copied = arr.slice();
console.log("arr", arr) //[1,2,[3,4]]
console.log("copied", copied) //[1,2,[3,4]]
copied[2].push(5)
copied.push(9)
console.log("arr", arr) //[1,2,[3,4,5]]
console.log("copied", copied) //[1,2,[3,4,5],9]
const str = "안녕하세요";
const strCopied = str.slice();
console.log(strCopied) //안녕하세요
깊은 복사
- 깊은 복사는 원본과 사본이 독립적으로 나눠서 복사하는 것
- 배열을 깊은 복사를 하려면 사용자 정의 함수를 만들어서 복사할수있다.
- 객체인 경우는 JSON.stringify() , JSON.parse() 사용한다 (배열은 사용 불가능)
- JSON.parse(string문자열) : JSON 포맷의 문자열을 객체로 변경해준다
- JSON.stringify(객체) : 객체를 JSON 포맷의 문자열로 바꿔준다
const ob = {안녕 : "안녕", name : "홍길동"};
const obCopy1 = JSON.stringify(ob) // 타입 : string
console.log(obCopy1); //{"안녕":"안녕","name":"홍길동"}
const type = typeof(obCopy1);
console.log(type) //string
const obCopy2 = JSON.parse(JSON.stringify(ob)) // 타입 : object
console.log(obCopy2); //{"안녕":"안녕","name":"홍길동"}
const type2 = typeof(obCopy2);
console.log(type2) //object
출처
https://bbaktaeho-95.tistory.com/37