
얕은 복사 는 여기서 ☑️
깊은 복사를 사용하면 중첩된 객체까지 복사해서 원본을 안전하게 보호할 수 있다.
structuredClone()은 중첩된 객체를 포함한 깊은 복사를 지원한다.
const obj = { a: { x: 1 } };
const copy = structuredClone(obj);
copy.a.x = 99;
console.log(obj.a.x); // 1 (원본은 유지됨)
const obj = { a: { x: 1 } };
const copy = JSON.parse(JSON.stringify(obj));
copy.a.x = 99;
console.log(obj.a.x); // 1 (원본은 유지됨)
한계:
https://lodash.com/docs/4.17.15#cloneDeep
const _ = require('lodash');
const obj = { a: { x: 1 } };
const copy = _.cloneDeep(obj);
copy.a.x = 99;
console.log(obj.a.x); // 1 (원본은 유지됨)
작은 객체라면 재귀적으로 복사하는 코드를 직접 작성할 수도 있다.
function deepCopy(obj) {
if (obj === null || typeof obj !== 'object') {
return obj; // 기본 자료형은 그대로 반환
}
const copy = Array.isArray(obj) ? [] : {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = deepCopy(obj[key]); //재귀적으로 복사
}
}
return copy;
}
const obj = { a: { x: 1 } };
const copy = deepCopy(obj);
copy.a.x = 99;
console.log(obj.a.x); // 1 (원본은 유지됨)
*Node.js: JavaScript를 서버나 로컬에서 실행할 수 있게 해주는 환경.
*재귀: 함수가 자기 자신을 다시 호출하는 것. 반복적인 작업을 수행할 때 많이 사용됨.
🛠️ 재귀와 반복문의 차이
// 재귀: 1부터 n까지의 합
function sumRecursive(n) {
if (n === 1) return 1; // 기저 조건
return n + sumRecursive(n - 1); //자기 자신 호출
}
// 반복문: 1부터 n까지의 합
function sumLoop(n) {
let sum = 0;
for (left i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
console.log(sumRecursive(5)); // 15
console.log(sumLoop(5)); // 15