
๐ข Destructuring Assignment๋ ๋ฐฐ์ด, ๋ฌธ์์ด๊ณผ ๊ฐ์ Iterable ๋๋ ๊ฐ์ฒด๋ฅผ destructuring(๊ตฌ์กฐ ํ๊ดด)ํ์ฌ 1๊ฐ ์ด์์ ๋ณ์์ ๊ฐ๋ณ์ ์ผ๋ก ํ ๋นํ๋ ๊ฒ์ ๋งํ๋ค.
๋ฐฐ์ด destructuring assignment์ ๋์์ iterable์ด์ด์ผ ํ๋ฉฐ, ํ ๋น ๊ธฐ์ค์ index์ด๋ค.
์์๋๋ก ํ ๋น๋๋ค.
const arr = [1, 2, 3];
// ๋ณ์ a, b, c๋ฅผ ์ ์ธํ๊ณ ๋ฐฐ์ด arr๋ฅผ destructuringํ์ฌ ํ ๋นํ๋ค.
const [a, b, c] = arr;
console.log(a, b, c); // 1, 2, 3
๋ณ์์ ๊ฐ์์ ์ดํฐ๋ฌ๋ธ์ ์์์ ๊ฐ์๊ฐ ๋ฐ๋์ ์ผ์นํ ํ์๋ ์๋ค.
const [a, b] = [1];
console.log(a, b); // 1 undefined
const [c, d] = [1, 2, 3];
console.log(c, d); // 1 2
const [e, ,f] = [1, 2, 3];
console.log(e, f); // 1 3
๋ณ์์ ๊ธฐ๋ณธ๊ฐ์ ์ค์ ํ ์ ์๋ค.
const [a, b, c = 5] = [1, 2];
console.log(a, b, c); // 1 2 5
// ๊ธฐ๋ณธ๊ฐ๋ณด๋ค ํ ๋น๊ฐ์ด ์ฐ์ ์ ๋๋ค.
const [d, e, f = 6] = [1, 2, 3];
console.log(d, e, f); // 1 2 3
๐ก ๋ฐฐ์ด์ arguement๋ก ๋ฐ๋ ํจ์์ parameter์๋ ์ฌ์ฉํ ์ ์๋ค.
์ด ๊ฒฝ์ฐ ์ฝ๋๋ฅผ ์ข ๋ ๊ฐ๊ฒฐํ๊ณ ๊ฐ๋ ์ฑ ์ข๊ฒ ํํํ ์ ์๋ค.
const arr = [1, 2, 3];
function print([a, b]) {
return `์ฒซ ๋ฒ์งธ๋ ${a}์ด๊ณ ๋ ๋ฒ์งธ๋ ${b}์ด๋ค.`;
}
print(arr); // '์ฒซ ๋ฒ์งธ๋ 1์ด๊ณ ๋ ๋ฒ์งธ๋ 2์ด๋ค.'
๋ณ์์ Rest parameter์ ์ ์ฌํ๊ฒ Rest element๋ฅผ ์ฌ์ฉํ ์ ์๋ค. ๋ฐ๋์ ๋ง์ง๋ง์ ์์นํด์ผ ํ๋ค.
const [a, ...b] = [1, 2, 3, 4];
console.log(a, b); // 1 [2, 3, 4]
๊ฐ์ฒด destructuring assignment์ ๋์์ object์ด์ด์ผ ํ๋ฉฐ, ํ ๋น ๊ธฐ์ค์ property์ key์ด๋ค.
์์๋ ์๋ฏธ ์๊ณ ๋ณ์ ์ด๋ฆ๊ณผ ํ๋กํผํฐ ํค๊ฐ ์ผ์นํ๋ฉด ํ ๋น๋๋ค.
const obj = { name: 'kim', age: 10 };
// ๋ณ์ name, age๋ฅผ ์ ์ธํ๊ณ ๊ฐ์ฒด obj๋ฅผ destructuringํ์ฌ ํ ๋นํ๋ค.
const {name, age} = obj;
console.log(name, age); // 'kim' 10
๋ณ์์ ๊ธฐ๋ณธ๊ฐ์ ์ค์ ํ ์ ์๋ค.
const obj = { name: 'kim', age: 10 };
const { name, age, gender = 'male' } = obj;
console.log(name, age, gender); // 'kim' 10 'male'
// ๊ธฐ๋ณธ๊ฐ๋ณด๋ค ํ ๋น๊ฐ์ด ์ฐ์ ์ ๋๋ค.
const { name = 'park', age } = obj;
console.log(name, age); // 'kim' 10
๐ก ๊ฐ์ฒด๋ฅผ arguement๋ก ๋ฐ๋ ํจ์์ parameter์๋ ์ฌ์ฉํ ์ ์๋ค.
์ด ๊ฒฝ์ฐ ์ฝ๋๋ฅผ ์ข ๋ ๊ฐ๊ฒฐํ๊ณ ๊ฐ๋ ์ฑ ์ข๊ฒ ํํํ ์ ์๋ค.
const obj = { name: 'kim', age: 10 };
function print({ name, age }) {
return `์ด๋ฆ์ ${name}์ด๊ณ ๋์ด๋ ${age}์ด๋ค.`;
}
print(obj); // '์ด๋ฆ์ kim์ด๊ณ ๋์ด๋ 10์ด๋ค.'
๋ฐฐ์ด ๊ตฌ์กฐ๋ถํดํ ๋น๊ณผ ๊ฐ์ฒด ๊ตฌ์กฐ๋ถํดํ ๋น์ ํผ์ฉํ ์๋ ์๋ค.
const list = [
{ id: 1, name: 'kim', age: 10 },
{ id: 2, name: 'park', age: 7 },
{ id: 3, name: 'lee', age: 12 },
];
const [, , { name }] = list;
console.log(name); // 'lee'
์ค์ฒฉ ๊ฐ์ฒด์์๋ ์ฌ์ฉ ๊ฐ๋ฅํ๋ค.
const person = {
name: 'kim',
address: {
country: 'korea',
city: 'seoul',
},
};
// address ํ๋กํผํฐ ํค๋ก ๊ฐ์ฒด๋ฅผ ์ถ์ถํ๊ณ ์ด ๊ฐ์ฒด์ city ํ๋กํผํฐ ํค๋ก ๊ฐ์ ์ถ์ถํ๋ค.
const {
address: { city },
} = person;
console.log(city); // 'seoul'
๋ณ์์ Rest parameter์ ์ ์ฌํ๊ฒ Rest property๋ฅผ ์ฌ์ฉํ ์ ์๋ค. ๋ฐ๋์ ๋ง์ง๋ง์ ์์นํด์ผ ํ๋ค.
const obj = {
a: 1,
b: 2,
c: 3,
d: 4,
};
const { a, ...rest } = obj;
console.log(a, rest); // 1 { b: 2, c: 3, d: 4 }
String ๋ํ iterable์ด๋ฏ๋ก destructuring assignment์ ๋์์ด๋ค.
const str = 'abcdefg'; const [first, second] = str; console.log(first, second); // 'a' 'b'