2021. 5. 12. 03:38ใ๐ป ๊ฐ๋ฐ/JavaScript
'๋ชจ๋ ์๋ฐ์คํฌ๋ฆฝํธ Deep Dive' (36์ฅ)์ ์ฝ๊ณ ์ ๋ฆฌํ ๊ธ์ ๋๋ค
๊ฐ์ฒด๋ฅผ 1๊ฐ ์ด์์ ๋ณ์์ ๊ฐ๋ณ์ ์ผ๋ก ํ ๋นํ๊ณ ์ถ์๋, ๊ฐ์ฒด ๋ฆฌํฐ๋ด์์ ํ์ํ ๊ฐ๋ง ์ถ์ถํ์ฌ ๋ณ์์ ํ ๋น์ํค๋ ๋ฐฉ์์ Destructuring Assignment, ๋์คํธ๋ญ์ฒ๋ง ํ ๋น์ด๋ผ๊ณ ํ๋ค.
์๋ฐ์คํฌ๋ฆฝํธ์์ ๋ฐฐ์ด๊ณผ ๊ฐ์ฒด๋ฅผ ๊ฐ๊ฐ ๋ถํ ํด์ ๋ณ์์ ํ ๋น์ํค๋ ๋ฐฉ์์ ์์๋ณด์.
1. ๋ฐฐ์ด ๋์คํธ๋ญ์ฒ๋ง (ES6 ๊ธฐ์ค)
const arr = [1, 2, 3];
// ES6 ๋ฐฐ์ด ๋์คํธ๋ญ์ฒ๋ง ํ ๋น
const [one, two, three] = arr;
console.log(one, two, three); // 1 2 3
์์ ์ฝ๋๋ฅผ ๋ณด๋ฉด ๋ณ์ one, two, three๋ฅผ ์ ์ธํ๊ณ ๋ฐฐ์ด arr๋ฅผ ๋น๊ตฌ์กฐํ(๋์คํธ๋ญ์ฒ๋ง) ํ์ฌ ๋ณ์์ ํ ๋น์์ผ ์ค๋ค.
๋ฐฐ์ด ๋์คํธ๋ญ์ฒ๋ง ํ ๋น์ ์ํด์๋ ๋ฐ๋์ ๋ณ์์ ํ ๋น ๋์ ์์ชฝ ๋ชจ๋ ๋ฐฐ์ด์ด์ด์ผ ํ๋ค.
const [x, y] = [1, 2];
let x, y;
[x, y] = [1, 2];
const [a, b] = [1, 2]
console.log(a, b) // 1 2
const [c, d] = [1];
console.log(c, d) // 1 undefined
const [e, f] = [1, 2, 3];
console.log(e, f) // 1 2
const [a, b, c = 3] = [1, 2];
console.log(a, b, c); // 1 2 3
const [e, f = 10, g = 3] = [1, 2];
console.log(e, f, g); // 1 2 3
๋ง์ฝ ์ฐ๋ณ์ ์ดํฐ๋ฌ๋ธ ํํ๋ก ํ ๋นํ์ง ์์ผ๋ฉด ๋ค์๊ณผ ๊ฐ์ ์๋ฌ๊ฐ ๋ฐ์ํ ๊ฒ์ด๋ค.
const [x, y];
const [a, b] = {}; // TypeError
{}๋ ์ดํฐ๋ฌ๋ธ์ด ์๋๊ธฐ๋๋ฌธ์ ๋ฐ์ํ๋ ์๋ฌ!
2. ๊ฐ์ฒด ๋์คํธ๋ญ์ฒ๋ง (ES6 ๊ธฐ์ค)
๊ฐ์ฒด์ ๋์คํธ๋ญ์ฒ๋ง ํ ๋น์ ๊ฒฝ์ฐ, ๊ฐ์ฒด ํ๋กํผํฐ์ ํค๊ฐ์ ์ฌ์ฉํด์ผ ํ๋ค.
const user = { firstName: 'Ahn', lastName: 'Lee' };
const { lastName, firstName } = user;
console.log(firstName, lastName); // Ahn Lee
๋ณ์๋ฅผ ์ ์ธํ๊ณ , user ๊ฐ์ฒด๋ฅผ ๋์คํธ๋ญ์ฒ๋ง ํ์ฌ ํ ๋น์์ผ์ค ๋ชจ์ต์ด๋ค.
const user = { firstName: 'Ahn', lastName: 'Lee' };
const { lastName: ln, firstName: fn } = user;
console.log(fn, ln); // Ahn Lee
๊ฐ์ฒด์ ํ๋กํผํฐ ํค์ ๋ค๋ฅธ ๋ณ์ ์ด๋ฆ์ผ๋ก ํ๋กํผํฐ ๊ฐ์ ํ ๋น๋ฐ์ผ๋ ค๋ฉด ์ด๋ ๊ฒ!
const { firstName = 'Ahn', lastName } = { lastName: 'Lee' };
console.log(fistName, lastName); // Ahn Lee
const todo = { id: 1, content: 'HTML', completed: true };
const { id } = todo;
console.log(id); // 1
์ด๋ ๊ฒ ๊ฐ์ฒด ๋์คํธ์ฒ๋ง์ ๊ฐ์ฒด์์ ํ๋กํผํฐ ํค๋ก ํ์ํ ๊ฐ๋ง ์ถ์ถํ๊ณ ์ถ์๋ ์ ์ฉํ๋ค
function printTodo(todo) {
console.log(`ํ ์ผ ${todo.content}์ ${todo.completed ? '์๋ฃ' : '๋น์๋ฃ'} ์ํ์
๋๋ค.`);
}
printTodo({ id: 1, content: 'HTML', completed: true}); // ํ ์ผ HTML์ ์๋ฃ ์ํ์
๋๋ค.
์ค์ ๋ก ์์๊ฐ์ด ์ฌ์ฉํ์๋ ๋งค๊ฐ๋ณ์๋ฅผ ๊ณ์ ๋ถ๋ฌ์์ผ ํด์ ๋ถํธํ๋๋ฐ
todo์ ๊ฐ์ฒด๋ค์ ํ ๋น์ํค๊ณ todo ํค์๋๋ฅผ ๋ฒ๋ฆฌ๊ณ ๊ฐ์ฒด๋ค๋ง ๋ถ๋ฌ์ค๋ฉด ์ข๋ ๊ฐ๋จํด์ง๋ค
function printTodo({ content, completed }) {
console.log(`ํ ์ผ ${content}์ ${completed ? '์๋ฃ' : '๋น์๋ฃ'} ์ํ์
๋๋ค.`);
}
printTodo({ id: 1, content: 'HTML', completed: true}); // ํ ์ผ HTML์ ์๋ฃ ์ํ์
๋๋ค.
๋ง์ง๋ง์ผ๋ก ์ค์ฒฉ๋ ๊ฐ์ฒด์์์ ๋์คํธ๋ญ์ฒ๋ง์ด๋ค.
const user = {
name: 'Lee',
address: {
zipCode: '03068',
city: 'Seoul'
}
};
const { address: { city } } = user;
console.log(city); // 'Seoul'
์ด ๊ฒฝ์ฐ์๋ address ํ๋กํผํฐ ํค๋ก ๋จผ์ ๊ฐ์ฒด๋ฅผ ์ถ์ถํ๊ณ , ์ด ๊ฐ์ฒด์ city ํ๋กํผํฐ ํค๋ก ๊ฐ์ ์ถ์ถํ๋ฉด ๋๋ค.
'๐ป ๊ฐ๋ฐ > JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
JavaScript ์คํ๋ ๋ ๋ฌธ๋ฒ ์์๋ณด๊ธฐ (0) | 2024.01.29 |
---|---|
JS๊ธฐ์ด | Ajax, JSON ๊ฐ๋ ์ ๋ฆฌ ๋ฐ ํ์ฉ๋ฐฉ๋ฒ (0) | 2021.08.24 |