본문 바로가기
Nodejs

Copy [Shallow, Deep]

by 마이네임이즈영우 2024. 10. 10.

배열이나 객체의 경우 일반변수와 달리 변수를 바로 할당하면 얕은 복사가 된다.

 

1. 깊은 복사  

별도의 변수를 만들어서 복사한다. 즉, 원본과 복사본은 별개로 사용된다.

일반변수를 할당할 경우이다.

 

let original = 1;

let copied = original;

copied += 4;

console.log(original); // 1

console.log(copied); // 5

 

2. 얕은 복사 

C의 포인터와 같은 개념으로 복사본의 변수에는 원본이 참조하는 주소가 들어가기 때문에 같은 값을 참조하게 된다.

즉, 원본과 복사본은 이름만 다르지 하나처럼 사용된다.

배열이나 객체의 경우 일반변수와 달리 변수를 바로 할당하면 얕은 복사가 된다.

 

let originalArray = [1, 2, 3, 4, 5];

let copiedArray = originalArray;

copiedArray[0] = 0;

console.log(originalArray); // [ 0, 2, 3, 4, 5 ]

console.log(copiedArray); // [ 0, 2, 3, 4, 5 ]

originalArray[1] = 7;

console.log(originalArray); // [ 0, 7, 3, 4, 5 ]

console.log(copiedArray); // [ 0, 7, 3, 4, 5 ]

 

 

배열이나 객체의 경우 전개연산자를 사용하여 깊은 복사를  할 수 있다.

const oArray = [1, 2, 3, 4]
const deepCopiedArray = [...oArray]
deepCopiedArray[0] = 0
console.log(oArray, deepCopiedArray) // [1, 2, 3, 4] [0, 2, 3, 4]

전개연산자는 배열의 값들을 복사하는 기능을 한다.

 

 

전개연산자 사용예.

let list = [];
let list1 = [1,2,3];
let list2 = [4,5,6];
ㅤ
list = [list1,list2];
console.log(list) // [[1,2,3], [4,5,6]]
ㅤ
list = [...list1,...list2];
console.log(list) // [1,2,3,4,5,6]

 

 

map과 함께 사용

const CardData = data.map((item) => {
  return <Card {...item} />;
  // return <Card item = {item} />;
  // return <Card openslote = {item.openslote} ...>
});
ㅤ
export default function App() {
  return (
    <div className="App">
      <section className="cardsList"> {CardData} </section>
    </div>
  );
}

 

Data가 다음과 같을 때

{
    id: 1,
    title: "Life Lessons with Katie Zaferes",
    description:
      'I will share with you',
    price: 136,
    stats: {
      rating: 5.0,
      reviewCount: 6
    },
    location: "Online",
    openSpots: 0
  },

 

<Card {...item} />의 경우  id, title, description ... 으로 복사가 된다. 즉 객체의 멤버들이 복사된다.

<Card item = {item} />의 경우 item 으로 복사된다. 즉 객체로 복사된다.

<Card title = {item.title} />의 경우 item.title이 title로 복사된다.

 

 

전개연산자는 배열의 값(Value)들을 복사하는 기능을 한다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'Nodejs' 카테고리의 다른 글

SPA, MPA  (0) 2024.10.11
CSR, SSR, SSC  (0) 2024.10.11
ts-node  (0) 2024.10.08
Prisma  (0) 2024.10.08
Supabase [슈파베이스]  (0) 2024.10.07