๋์คํธ๋ญ์ฒ๋ง ํ ๋น
- ๋์คํธ๋ญ์ฒ๋ง ํ ๋น(๊ตฌ์กฐ ๋ถํด ํ ๋น,
destructuring assignment
)์ ๊ตฌ์กฐํ๋ ๋ฐฐ์ด๊ณผ ๊ฐ์ ์ดํฐ๋ฌ๋ธ ๋๋ ๊ฐ์ฒด๋ฅผ destructuring
ํ์ฌ 1๊ฐ ์ด์์ ๋ณ์์ ๊ฐ๋ณ์ ์ผ๋ก ํ ๋นํ๋ ๊ฒ์ ๋งํ๋ค.
- ๋ฐฐ์ด๊ณผ ๊ฐ์ ์ดํฐ๋ฌ๋ธ ๋๋ ๊ฐ์ฒด ๋ฆฌํฐ๋ด์์ ํ์ํ ๊ฐ๋ง ์ถ์ถํ์ฌ ๋ณ์์ ํ ๋นํ ๋ ์ ์ฉ
๋ฐฐ์ด ๋์คํธ๋ญ์ฒ๋ง ํ ๋น
- ๋ฐฐ์ด์ ๊ฐ ์์๋ฅผ ๋ฐฐ์ด๋ก๋ถํฐ ์ถ์ถํ์ฌ 1๊ฐ ์ด์์ ๋ณ์์ ํ ๋น
- ๋์คํธ๋ญ ์ฒ๋ง ํ ๋น์ ๋์(ํ ๋น๋ฌธ์ ์ฐ๋ณ)์ ์ดํฐ๋ฌ๋ธ์ด์ด์ผ ํ๋ค.
const arr = [1,2,3];
const [one, two, three] = arr;
console.log(one, two, three); // 1 2 3
- ํ ๋น์ ๊ธฐ์ค์ ์ธ๋ฑ์ค์ด๋ค. ์ฆ, ์์๋๋ก ํ ๋น๋๊ณ ๋ณ์์ ๊ฐ์์ ์ผ์นํ ํ์๋ ์๋ค.
- ํ ๋น๋๋ ๋ณ์์ ๊ธฐ๋ณธ ๊ฐ์ ์ค์ ํ ์ ์๊ณ , ๊ธฐ๋ณธ๊ฐ ๋ณด๋ค ํ ๋น๋ ๊ฐ์ด ์ฐ์ ํ๋ค.
const [a, b, c=3] = [1,2];
cosole.log(a,b,c); // 1 2 3
const [a,b,c=3] = [1,2,4];
cosole.log(a,b,c); // 1 2 4
๊ฐ์ฒด ๋์คํฐ๋ญ์ฒ๋ง ํ ๋น
- ๊ฐ์ฒด์ ๊ฐ ํ๋กํผํฐ๋ฅผ ๊ฐ์ฒด๋ก ๋ถํฐ ์ถ์ถํ์ฌ 1๊ฐ ์ด์์ ๋ณ์์ ํ ๋นํ๋ค.
- ํ ๋น์ ๋์(ํ ๋น๋ฌธ์ ์ฐ๋ณ)์ ๊ฐ์ฒด์ด์ด์ผ ํ๋ฉฐ, ํ ๋น ๊ธฐ์ค์ ํ๋กํผํฐ ํค๋ค. ์ฆ, ์์๋ ์๋ฏธ๊ฐ ์์ผ๋ฉฐ, ์ ์ธ๋ ๋ณ์ ์ด๋ฆ๊ณผ ํ๋กํผํฐ ํค๊ฐ ์ผ์นํ๋ฉด ํ ๋น ๋๋ค.
const user = {
firstName : 'homie',
lastName : 'kim'
};
// ํ๋กํผํฐํค๋ฅผ ๊ธฐ์ค์ผ๋ก ํ ๋น์ด ์ด๋ฃจ์ด์ง
const {lastName, firstName} = user;
console.log(firstName, lastName); // homie kim
// ๊ฐ์ฒด๋ฆฌํฐ๋ด ํํ๋ก ์ ์ธ๋ ๋ณ์๋ ํ๋กํผํฐ ์ถ์ฝ ํํ์ ํตํด ์ ์ธ๋ ๊ฒ
const { lastName: lastName , firstName : firstName} = user;
// ํ๋กํผํฐ์ ํค์ ๋ค๋ฅธ ์ด๋ฆ์ผ๋ก ๋ณ์๋ฅผ ๋ฐ์ผ๋ ค๋ฉด ๋ค์๊ณผ ๊ฐ์ด ๋ณ์ ์ ์ธ
const { lastName : ln, firstName : fn} = user;
console.log(fn, ln); // homie kim
- ๋ฐฐ์ด์ ์์๊ฐ ๊ฐ์ฒด์ธ ๊ฒฝ์ฐ ๋ฐฐ์ด ๋์คํธ๋ญ์ฒ๋ง ํ ๋น๊ณผ ๊ฐ์ฒด ๋์คํธ๋ญ์ฒ๋ง ํ ๋น์ ํผ์ฉํ ์ ์๋ค.
const todos = [
{ id : 1, content : 'HTML', completed : true},
{ id : 2, content : 'CSS', completed : false},
{ id : 3, content : 'JS', completed : true},
];
// ๋ฐฐ์ด ๋์คํธ๋ญ์ฒ๋ง ๊ธฐ์ค์ ์ธ๋ฑ์ค, ๊ฐ์ฒด ๋์คํธ๋ญ์ฒ๋ง ๊ธฐ์ค์ ํ๋กํผํฐ ํค
const [, {id},{content}] = todos;
console.log(id, content); // 2 JS
๋๊ธ