๋์คํธ๋ญ์ฒ๋ง ํ ๋น
- ๋์คํธ๋ญ์ฒ๋ง ํ ๋น(๊ตฌ์กฐ ๋ถํด ํ ๋น,
destructuring assignment
)์ ๊ตฌ์กฐํ๋ ๋ฐฐ์ด๊ณผ ๊ฐ์ ์ดํฐ๋ฌ๋ธ ๋๋ ๊ฐ์ฒด๋ฅผ destructuring
ํ์ฌ 1๊ฐ ์ด์์ ๋ณ์์ ๊ฐ๋ณ์ ์ผ๋ก ํ ๋นํ๋ ๊ฒ์ ๋งํ๋ค.
- ๋ฐฐ์ด๊ณผ ๊ฐ์ ์ดํฐ๋ฌ๋ธ ๋๋ ๊ฐ์ฒด ๋ฆฌํฐ๋ด์์ ํ์ํ ๊ฐ๋ง ์ถ์ถํ์ฌ ๋ณ์์ ํ ๋นํ ๋ ์ ์ฉ
๋ฐฐ์ด ๋์คํธ๋ญ์ฒ๋ง ํ ๋น
- ๋ฐฐ์ด์ ๊ฐ ์์๋ฅผ ๋ฐฐ์ด๋ก๋ถํฐ ์ถ์ถํ์ฌ 1๊ฐ ์ด์์ ๋ณ์์ ํ ๋น
- ๋์คํธ๋ญ ์ฒ๋ง ํ ๋น์ ๋์(ํ ๋น๋ฌธ์ ์ฐ๋ณ)์ ์ดํฐ๋ฌ๋ธ์ด์ด์ผ ํ๋ค.
| const arr = [1,2,3]; |
| |
| const [one, two, three] = arr; |
| console.log(one, two, three); |
- ํ ๋น์ ๊ธฐ์ค์ ์ธ๋ฑ์ค์ด๋ค. ์ฆ, ์์๋๋ก ํ ๋น๋๊ณ ๋ณ์์ ๊ฐ์์ ์ผ์นํ ํ์๋ ์๋ค.
- ํ ๋น๋๋ ๋ณ์์ ๊ธฐ๋ณธ ๊ฐ์ ์ค์ ํ ์ ์๊ณ , ๊ธฐ๋ณธ๊ฐ ๋ณด๋ค ํ ๋น๋ ๊ฐ์ด ์ฐ์ ํ๋ค.
| const [a, b, c=3] = [1,2]; |
| cosole.log(a,b,c); |
| |
| const [a,b,c=3] = [1,2,4]; |
| cosole.log(a,b,c); |
๊ฐ์ฒด ๋์คํฐ๋ญ์ฒ๋ง ํ ๋น
- ๊ฐ์ฒด์ ๊ฐ ํ๋กํผํฐ๋ฅผ ๊ฐ์ฒด๋ก ๋ถํฐ ์ถ์ถํ์ฌ 1๊ฐ ์ด์์ ๋ณ์์ ํ ๋นํ๋ค.
- ํ ๋น์ ๋์(ํ ๋น๋ฌธ์ ์ฐ๋ณ)์ ๊ฐ์ฒด์ด์ด์ผ ํ๋ฉฐ, ํ ๋น ๊ธฐ์ค์ ํ๋กํผํฐ ํค๋ค. ์ฆ, ์์๋ ์๋ฏธ๊ฐ ์์ผ๋ฉฐ, ์ ์ธ๋ ๋ณ์ ์ด๋ฆ๊ณผ ํ๋กํผํฐ ํค๊ฐ ์ผ์นํ๋ฉด ํ ๋น ๋๋ค.
| const user = { |
| firstName : 'homie', |
| lastName : 'kim' |
| }; |
| |
| const {lastName, firstName} = user; |
| console.log(firstName, lastName); |
| |
| const { lastName: lastName , firstName : firstName} = user; |
| |
| const { lastName : ln, firstName : fn} = user; |
| console.log(fn, ln); |
- ๋ฐฐ์ด์ ์์๊ฐ ๊ฐ์ฒด์ธ ๊ฒฝ์ฐ ๋ฐฐ์ด ๋์คํธ๋ญ์ฒ๋ง ํ ๋น๊ณผ ๊ฐ์ฒด ๋์คํธ๋ญ์ฒ๋ง ํ ๋น์ ํผ์ฉํ ์ ์๋ค.
| const todos = [ |
| { id : 1, content : 'HTML', completed : true}, |
| { id : 2, content : 'CSS', completed : false}, |
| { id : 3, content : 'JS', completed : true}, |
| ]; |
| |
| const [, {id},{content}] = todos; |
| console.log(id, content); |
๋๊ธ