A deep copy means that all of the values of the new variable are copied and disconnected from the original variable.
A shallow copy means that certain (sub-)values are still connected to the original variable.
let fruits = {
orange : 2,
apple : 3,
banana : 10,
'shine muscat' : 1000
};
let eatFruits = fruits;
eatFruits['shine muscat'] = 99;
console.log(eatFruits['shine muscat']); // 결과 99
console.log(fruits['shine muscat']); // 결과 99
let fruits = {
orange : 2,
apple : 3,
banana : 10,
'shine muscat' : 1000
};
let buyFruits = {...fruits};
buyFruits.orange = 12;
console.log(fruits.orange); // 결과 2
console.log(buyFruits.orange); // 결과 12
let fruits = {
orange : 2,
apple : 3,
banana : 10,
'shine muscat' : 1000,
};
let copyFruits = Object.assign({},fruits);
copyFruits.orange = 12;
console.log(fruits.orange); // 결과 2
console.log(copyFruits.orange); // 결과 12
When you have a nested object (or array) and you copy it, nested objects inside that object will not be copied, since they are only pointers / references. Therefore, if you change the nested object, you will change it for both instances, meaning you would end up doing a shallow copy again.
let fruits = {
orange : 2,
apple : 3,
banana : 10,
'shine muscat' : 1000
tropical: {
Durian : 3
}
};
let copyFruits = {...fruits};
copyFruits.tropical.Durian = 10;
// copyFruits.tropical.Durian은 fruits.tropical.Durian과 같은 주소값을 가지기 때문에 copyFruits안의 객체의 속성 값을 변경하면 fruits안의 객체의 값도 같이 변경되어 shallow copy이다.
console.log(fruits.tropical.Durian); // 결과 10
console.log(copyFruits.tropical.Durian) // 결과 10
let fruits = {
orange : 2,
apple : 3,
banana : 10,
'shine muscat' : 1000,
tropical: {
Durian : 3
}
};
let copyFruits = {
orange : 2,
apple : 3,
banana : 10,
'shine muscat' : 1000,
tropical: {...fruits.tropical}
};
copyFruits.tropical.Durian = 10;
console.log(fruits.tropical.Durian); // 결과 3
console.log(copyFruits.tropical.Durian) // 결과 10
const a = {
foods: {
dinner: 'Pasta'
}
}
let b = JSON.parse(JSON.stringify(a))
b.foods.dinner = 'Soup'
console.log(b.foods.dinner) // Soup
console.log(a.foods.dinner) // Pasta
let arr = [1,2,3];
let arrCopy = [...a];
arrCopy[1] = 3;
console.log(arr[1]); // 2
console.log(arrCopy[1]); //3
//map
let arr = [1,2,3];
let arrCopy = arr.map(function(el){
return el;
});
arrCopy[1] = 3;
console.log(arr[1]); // 2
console.log(arrCopy[1]); //3
//filter
let arr = [1,2,3];
let arrCopy = arr.filter(function(el){
return true;
});
arrCopy[1] = 3;
console.log(arr[1]); // 2
console.log(arrCopy[1]); //3
let arr = [1,2,3];
let arrCopy = arr.slice();
arrCopy[1] = 3;
console.log(arr[1]); // 2
console.log(arrCopy[1]); //3