JS 달리기반 2회차 정리

slppills·2024년 7월 25일

TIL

목록 보기
33/69

참조형 타입이란?

참조형 타입은 메모리에 값이 저장된 주소를 참조하는 타입이다. 자바스크립트에서 참조형은 객체, 배열, 함수 등이 있다. 참조형 타입은 값을 직접 가지지 않고, 해당 값이 저장된 메모리 주소를 가리킨다.
따라서, 같은 참조형 타입 변수를 여러개 만들면 모두 동일한 메모리 주소를 가리키기 때문에 한 변수를 수정하면 다른 변수에도 영향을 미칠 수 있다.

배열 복사하기

배열을 복사할 때 얕은 복사와 깊은 복사 두 가지 방법이 있다.

얕은 복사(Shallow Copy)

얕은 복사는 배열의 참조를 복사하는 것으로, 원본 배열과 복사된 배열이 동일한 객체를 참조한다. 따라서 한 배열을 수정하면 다른 배열에도 영향을 미친다.

let original = ['Apple', 'Banana', 'Cherry'];
let shallowCopy = original;

shallowCopy[1] = 'Blueberry';
console.log(original); // ['Apple', 'Blueberry', 'Cherry']
console.log(shallowCopy); // ['Apple', 'Blueberry', 'Cherry']

깊은 복사(Deep Copy)

깊은 복사는 배열의 모든 요소를 새로운 배열에 복사하여 원본 배열과 복사된 배열이 서로 다른 객체를 참조하게 만든다. 깊은 복사를 하면 한 배열을 수정해도 다른 배열에 영향을 미치지 않는다.

  • 재귀적 복제
function deepCopy(o) {
  var result = {};
  if (typeof o === "object" && o !== null)
    for (i in o) result[i] = deepCopy(o[i]);
  else result = o;
  return result;
}

const obj1 = {
  a: 1,
  b: [1, 2, 3]
};

var obj2 = deepCopy(obj1);

console.log(obj1 === obj2);
console.log(obj1);
console.log(obj2);
  • JSON.parse, JSON.stringify 로 복사
    • 깊은 복사는 가능하지만 gettser/setter 등 JSON 으로 변경할 수 없는 프로퍼티는 무시한다. 배열도 깊은 복사가 가능하지만 배열 관련 함수는 사용 불가능하다.
let original = ['Apple', 'Banana', 'Cherry'];
let deepCopy = JSON.parse(JSON.stringify(original));

deepCopy[1] = 'Blueberry';
console.log(original); // ['Apple', 'Banana', 'Cherry']
console.log(deepCopy); // ['Apple', 'Blueberry', 'Cherry']

객체의 복사도 배열을 복사하는 방법과 같다.

0개의 댓글