Today's Finding
Shallow vs. Deep Copying Objects
paigekim29
2020. 11. 5. 10:56
Shallow Copying Objects:
- Will duplicate the top-level properties but nested object is shared between original and the copy
- Array.prototype.slice()
12345678910const arr = ['peanut', 'butter', 'and', 'jelly'];arr.slice(1); // ['butter', 'and', 'jelly']arr.slice(0, 1); // ['peanut']arr.slice(0, 2); // ['peanut', 'butter']arr.slice(2, 2); // []arr.slice(2, 20); // ['and', 'jelly']arr.slice(3, 0);// []arr.slice(3, 100);// ['jelly']arr.slice(5, 1); // []
cs - Object.assgin()
- Object.assign({}, arr)
- will affect 'array inside array' if it modifies since it is shallow copying objects
- Pitfall: ๊ณ์ ์ํ ์ฐธ์กฐ
Deep Copying Objects:
- JSON.parse(JSON.stringify(object))
- Pitafall: if you put user's method, it will cause an error.
- ์๋ฒ ํต์ ์์๋ ๋ฎ์นดํผ๊ฐ ๋ง์
- ์๋ฐ์คํฌ๋ฆฝํธ๋ ๊ฐ์ฒด๋ ๋ฐฐ์ด์ด ์๋๋ผ ๊ทธ๋ฅ ๊ธ์์
reference: