destructuring-assignment
๊ตฌ์กฐ ๋ถํด ํ ๋น
๊ฐ์ฒด๋ ๋ฐฐ์ด์ ๋ณ์๋ก ๋ถํด
ํ ์ ์๊ฒ ํด์ฃผ๋ ํน๋ณํ ๋ฌธ๋ฒ
๋ฐฐ์ด ๋ถํด
์ฌ์ฉ๋ฒ
let arr = ['Bora', 'Lee'];
let [firstName = 'First', surname = 'last'] = arr;
alert(firstName); // Bora
alert(surname); // Lee
ํน์ง
์ฐ์ธก์๋ ๋ฐฐ์ด ๋ฟ๋ง์ด ์๋ ๋ชจ๋ ์ดํฐ๋ฌ๋ธ์ด ์ฌ ์ ์๋ค.
let [firstName, surname] = 'Bora Lee'.split(' '); alert(firstName); // Bora alert(surname); // Lee
let [one, two, three] = new Set([1, 2, 3]);
๋ณ์ ๊ตํํ๋๋ฐ ์ฌ์ฉํ ์ ์๋ค.
let guest = 'Jane'; let admin = 'Pete'; [guest, admin] = [admin, guest];
...
์ผ๋ก ๋๋จธ์ง ์์๋ฅผ ๋ฐฐ์ด๋ก ๊ฐ์ ธ์ฌ ์ ์๋ค.let [name1, name2, ...rest] = ['kim', 'lee', 'hong', 'No']; alert(rest.length); //2
ํ ๋นํ ๊ฐ์ด ์์ผ๋ฉด
undefined
์ทจ๊ธํ๋คlet [first, last] = []; alert(first); //undefined alert(last); //undefined
๊ฐ์ฒด ๋ถํด
์ฌ์ฉ๋ฒ
let {var1, var2} = {var1:โฆ, var2:โฆ}
์๋ ๋ณด์ด๋ ๊ฒ์ฒ๋ผ ์์๊ฐ ๋ฐ๋์ด๋ key์ ์์ํ๋ ๋ณ์์ ์ฐ๊ฒฐ์ด ๋๋ค.
let { height, width, title } = { title: 'Menu', height: 200, width: 100 };
alert(title); // Menu
alert(width); // 100
alert(height); // 200
ํน์ง
๋ณ์๋ช ์ key๊ฐ์ด ์๋ ๋ชฉํ ๋ณ์(
๋ณ์นญ
)๋ก ์ค์ ํ ์ ์๋ค.let options = { title: 'Menu', width: 100, height: 200, }; let { width: w, height: h, title } = options; // width -> w // height -> h // title -> title alert(title); // Menu alert(w); // 100 alert(h); // 200
let์ผ๋ก ์๋ก์ด ๋ณ์ ์ ์ธ์ด ์๋ ๊ธฐ์กด ๋ณ์๋ฅผ ์ด์ฉํด ํ ๋น์ด ๊ฐ๋ฅํ๋ค
({ title, width, height } = { title: 'Menu', width: 200, height: 100 });
์ด๋,
()
๋ก ์๋ฌถ์ด ์ฃผ๋ฉด{}
๋ฅผ ํํ์์ด ์๋ ์ฝ๋๋ธ๋ญ์ผ๋ก ์ธ์ํ์ฌ ์๋ฌ๊ฐ ๋๋ค.ํจ์์ ์ธ์๋ก ๊ฐ์ฒด๋ฅผ ์ ๋ฌ์ ์๋์ผ๋ก ๋ถํดํด์ ์ฌ์ฉํ๋ค.
let options = { title: 'My menu', items: ['Item1', 'Item2'], }; function showMenu({ title = 'Menu', width = 100, height = 200 } = {}) { alert(`${title} ${width} ${height}`); } showMenu(); // Menu 100 200
Last updated