2019๋ 4์ 11์ผ
Destructuring์ ๋ฐฐ์ด ๋๋ ๊ฐ์ฒด์์ ํ์ํ ๊ฐ๋ง ์ถ์ถํ์ฌ ๋ณ์์ ํ ๋นํ๋ ๊ฒ์ ๋งํ๋ค.
- ๋ฐฐ์ด ๋์คํธ๋ญ์ฒ๋ง์ ์ถ์ถ / ํ ๋น ๊ธฐ์ค์ ๋ฐฐ์ด์ ์ธ๋ฑ์ค์ด๋ค.
// ES5 Destructuring
var arr = [1, 2, 3];
var one = arr[0];
var two = arr[1];
var three = arr[2];
console.log(one, two, three); // 1 2 3
// ES6 Destructuring
const arr = [1, 2, 3];
// ๋ฐฐ์ด์ ์ธ๋ฑ์ค๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ฐฐ์ด๋ก๋ถํฐ ์์๋ฅผ ์ถ์ถํ์ฌ ๋ณ์์ ํ ๋น
const [one, two, three] = arr;
console.log(one, two, three); // 1 2 3
let a, b, c;
[a, b, c] = [1, 2, 3];
// ์์ ๊ตฌ๋ฌธ๊ณผ ๋์ผํ๋ค
let [a, b, c] = [1, 2, 3];
let a, b, c;
[a, b] = [1, 2];
console.log(a, b); // 1 2
[a, b] = [1];
console.log(a, b); // 1 undefined
[a, b] = [1, 2, 3];
console.log(a, b); // 1 2
[a, , c] = [1, 2, 3];
console.log(a, c); // 1 3
// ๊ธฐ๋ณธ๊ฐ
[a, b, c = 3] = [1, 2];
console.log(a, b, c); // 1 2 3
[a, b = 10, c = 3] = [1, 2];
console.log(a, b, c); // 1 2 3
// spread ์ฐ์ฐ์
[a, ...c] = [1, 2, 3];
console.log(a, b); // 1 [ 2, 3 ]
- ES6์ ๋ฐฐ์ด ๋์คํธ๋ญ์ฒ๋ง์ ๋ฐฐ์ด์์ ํ์ํ ์์๋ง ์ถ์ถํ์ฌ ๋ณ์์ ํ ๋นํ๊ณ ์ถ์ ๊ฒฝ์ฐ์ ์ ์ฉํ๋ค.
- ์๋์ ์ฝ๋๋ Date ๊ฐ์ฒด์์ ๋ ๋, ์, ์ผ์ ์ถ์ถํ๋ ์์ ์ด๋ค.
const today = new Date();
console.log(today); // 2019-05-01T15:38:25.837Z
const formattedDate = today.toISOString().substring(0, 10);
console.log(formattedDate); // 2019-05-01
const [year, month, day] = formattedDate.split('-');
console.log([year, month, day]); // [ '2019', '05', '01' ]
- ๊ฐ์ฒด ๋์คํธ๋ญ์ฒ๋ง์ ์ถ์ถ / ํ ๋น ๊ธฐ์ค์ ๊ฐ์ฒด์ ํค(key)๊ฐ์ด๋ค.
// ES5 Destructuring
var obj = { firstName: 'Sony', lastName: 'Park' };
var firstName = obj.firstName;
var lastName = obj.lastName;
console.log(firstName, lastName); // Sony Park
// ES6 Destructuring
const obj = { firstName: 'Sony', lastName: 'Park' };
const { firstName, lastName } = obj;
console.log(firstName, lastName); // Sony Park
const { key1, key2 } = { key1 : 'a', key2 : 'b' };
console.log({ key1, key2 }); // { key1 : 'a', key2 : 'b' }
//defalut value
const { key1, key2, key3 = 'c' } = { key1 : 'a', key2 : 'b' };
console.log({ key1, key2, key3 }); // { key1 : 'a', key2 : 'b', key3 : 'c' }
- Array.prototype.filter ๋ฉ์๋์ ์ฝ๋ฐฑ ํจ์๋ ๋์ ๋ฐฐ์ด(todos)์ ์ํํ๋ฉฐ ์ฒซ ๋ฒ์งธ ์ธ์๋ก ๋์ ๋ฐฐ์ด์ ์์๋ฅผ ๋ฐ๋๋ค. ์ด๋ ํ์ํ ํ๋กํผํฐ(key)(completed ํ๋กํผํฐ)๋ง์ ์ถ์ถํ ์ ์๋ค.
const todos = [
{ id: 1, content: 'HTML', completed: true },
{ id: 2, content: 'CSS', completed: false },
{ id: 3, content: 'JS', completed: false }
];
// todos ๋ฐฐ์ด์ ์์์ธ ๊ฐ์ฒด๋ก๋ถํฐ completed ํ๋กํผํฐ๋ง์ ์ถ์ถํ๋ค.
const completedTodos = todos.filter(({ completed }) => completed);
console.log(completedTodos); // [ { id: 1, content: 'HTML', completed: true } ]
- ์ค์ฒฉ ๊ฐ์ฒด์ ๊ฒฝ์ฐ ๋ค์๊ณผ ๊ฐ์ด ์ฌ์ฉํ๋ค.
const person = {
name: 'Sony',
address: {
zipCode: '06219',
city: 'Seoul'
}
};
const { address: { city } } = person;
console.log(city); // 'Seoul'