๐ฅ ๋์คํธ๋ญ์ฒ๋ง ํ ๋น
๋์คํธ๋ญ์ฒ๋ง ํ ๋น์ ๊ตฌ์กฐํ๋ ๋ฐฐ์ด๊ณผ ๊ฐ์ ์ดํฐ๋ฌ๋ธ์ด๋ ๊ฐ์ฒด๋ฅผ destructuring(๋น๊ตฌ์กฐํ, ๊ตฌ์กฐ ํ๊ดด)ํ์ฌ 1๊ฐ ์ด์์ ๋ณ์์ ๊ฐ๋ณ์ ํ ๋น ํ๋ ๊ฒ์ ์ด์ผ๊ธฐํ๋ค.
๐ฅ ๋ฐฐ์ด ๋์คํธ๋ญ์ฒ๋ง
// es5
const arr = [1, 2, 3]
const one = arr[0]
const two = arr[1]
const three = arr[2]
console.log(one, two, three); // 1 2 3
//es6
const arr = [1, 2, 3]
const [one, two, three] = arr;
console.log(one, two, three); // 1 2 3
๋ฐฐ์ด ๋์คํธ๋ญ์ฒ๋ง ํ ๋น์ ๋์(ํ ๋น๋ฌธ์ ์ฐ๋ณ)์ ์ดํฐ๋ฌ๋ธ ์ด์ด์ผ ํ๋ฉฐ, ํ ๋น ๊ธฐ์ค์ ๋ฐฐ์ด์ ์ธ๋ฑ์ค๋ค.
์ผ์ชฝ์ ๋ณ์๋ฅผ ๋ฐฐ์ด ๋ฆฌํฐ๋ด ํํ๋ก ์ ์ธํ๊ณ ์ค๋ฅธ์ชฝ์ ์ดํฐ๋ฌ๋ธ์ ํ ๋นํ๋ค.
const [x, y]; // ์ค๋ฅ
const [a, b] = {}; // ์ค๋ฅ (์ดํฐ๋ฌ๋ธ ์๋๋ผ)
์์ ๋งํ๊ฒ ์ฒ๋ผ ๋ฐฐ์ด ๋์คํธ๋ญ์ฒ๋ง ํ ๋น์ ๊ธฐ์ค์ ๋ฐฐ์ด์ ์ธ๋ฑ์ค๋ค. ์ฆ, ์์๋๋ก ํ ๋น๋๋ค.
๋ณ์์ ๊ฐ์์ ์ดํฐ๋ฌ๋ธ์ ์์ ๊ฐ์๊ฐ ๋ฐ๋์ ์ผ์นํ ํ์๋ ์๋ค.
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 = 10, c = 3] = [1, 2];
console.log(a, b, c); // 1, 2, 3
๐ฅ ๊ฐ์ฒด ๋์คํธ๋ญ์ฒ๋ง ํ ๋น
ES6์ ๊ฐ์ฒด ๋์คํธ๋ญ์ฒ๋ง ํ ๋น์ ๊ฐ์ฒด์ ๊ฐ ํ๋กํผํฐ๋ฅผ ๊ฐ์ฒด๋ก๋ถํฐ ์ถ์ถํ์ฌ 1๊ฐ ์ด์์ ๋ณ์์ ํ ๋นํ๋ค.
๊ฐ์ฒด ๋์คํธ๋ญ์ฒ๋ง ํ ๋น์ ๋์(ํ ๋น๋ฌธ์ ์ฐ๋ณ)์ ๊ฐ์ฒด์ด์ด์ผ ํ๋ฉฐ, ํ ๋น๊ธฐ์ค์ ํ๋กํผํฐ ํค์ด๋ค. ๋ฐฐ์ด๊ณผ ๋ค๋ฅด๊ฒ, ์์๋ ์๋ฏธ ์์ผ๋ฉฐ ์ ์ธ๋ ๋ณ์ ์ด๋ฆ๊ณผ ํ๋กํผํฐ ํค๊ฐ ์ผ์นํ๋ฉด ํ ๋น๋๋ค.
const user = { firstName: 'Choi', lastName: 'Elice' };
const { lastName, firstName } = user;
console.log(firstName, lastName); // Choi Elice
๊ฐ์ฒด ๋์คํธ๋ญ์ฒ๋ง ํ ๋น์ ๊ฐ์ฒด์์ ํ๋กํผํฐ ํค๋ก ํ์ํ ํ๋กํผํฐ ๊ฐ๋ง ์ถ์ถํ์ฌ ๋ณ์์ ํ ๋นํ๊ณ ์ถ์ ๋ ์ ์ฉํ๋ค.
const str = 'Hello';
const { length } = str;
console.log(length); // 5
const todo = { id: 1, content: 'HTML', completed: true };
const { id } = todo;
console.log(id); // 1
// ์ ๋ฌ๋ฐ์ (todo) ๋์ ์ ๋ฐ์ ์ฒ๋ผ ๊ฐ์ฒด ๊ตฌ์กฐ๋ถํดํ ๋น์ ์ฌ์ฉํ๋ฉด ์ข ๋ ๊ฐ๋จํ๊ณ ๊ฐ๋
์ด ์ข๋ค.
function printTodo({ content, completed }) {
console.log(`ํ ์ผ ${content}์ ${completed ? "์๋ฃ" : "๋น์๋ฃ"} ์ํ์
๋๋ค.`);
}
printTodo({ id: 1, content: 'HTML', completed: true });
๋ฐฐ์ด์ ์์๊ฐ ๊ฐ์ฒด์ธ ๊ฒฝ์ฐ ๋ฐฐ์ด ๋์คํธ๋ญ์ฒ๋ง ํ ๋น๊ณผ ๊ฐ์ฒด ๋์คํธ๋ญ์ฒ๋ง ํ ๋น์ ํผ์ฉํ ์ ์๋ค.
const todos = [
{ id: 1, content: 'HTML', completed: true },
{ id: 2, content: 'CSS', completed: false },
{ id: 3, content: 'JS', completed: false }
];
const [, { id }] = todos;
console.log(id); // 2
const user = {
name: 'Park',
address: {
zipCode: '03068',
city: 'Seoul'
}
}
const { address: { city } } = user;
console.log(city); // 'Seoul'
๊ฐ์ฒด ๋์คํธ๋ญ์ฒ๋ง ํ ๋น์ ์ํ ๋ณ์ Rest ํ๋ผ๋ฏธํฐ๋ Rest ์์์ ์ ์ฌํ๊ฒ Rest ํ๋กํผํฐ ...์ ์ฌ์ฉํ ์ ์๋ค.
const {x, ...rest} = { x: 1, y: 2, z: 3 }
console.log(x, rest); // 1, { y: 2, z: 3 }
'Elice > Study' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JavaScript] DOM (0) | 2024.03.21 |
---|---|
[JavaScript] this (์ ์ , ๋์ ๋ฐ์ธ๋ฉ) (0) | 2024.03.21 |
[JavaScript] ๋๋จธ์ง ๋งค๊ฐ ๋ณ์์ ๊ตฌ๋ฌธ (0) | 2024.03.21 |
[JavaScript] ํด๋ก์ (Closure) (0) | 2024.03.21 |
[React] SPA, ๋ผ์ฐํ (0) | 2024.03.15 |