구조 분해 할당이란?
구조 분해 할당 구문은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식입니다.
-> 구조 분해 할당 mdn
const [a,b, ...args] = [10,20,30,40,50,60,70]
console.log(a) => 10
console.log(b) => 20
console.log(args) => [30,40,50,60,70]
위에 코드는 a,b 값으로 10,20, 할당하고, 나머지는 '...args'로 배열로 묶어서 값이 할당되었다.
cosole.log(args[1]) => 40 이다.
const {a,b,...args} = {a: 10, b: 20, c:30, d:40, e:70}
console.log(a) => 10
console.log(b) => 20
console.log(c) => error
console.log(args) => {c: 30, d: 40, e: 70}
console.log({a,b,...args}) => {a: 10, b: 20, c: 30, d: 40, e: 70}
const obj = {a,b,...args}
console.log(obj.c) => 30
객체를 여러값 할당할 때는 '...args'로 할당 되었던 값은 console.log로 바로 접근을 하지 못했다.
console.log(args)로 나머지 값에 접근 하는 방법이나, 따로 선언한 변수에 묶음으로 담아야 접근 할 수 있었다.
function f() {
return [1,2,3,4,5,6,6,];
}
const [a, b, ...args] = f();
console.log(a); // 1
console.log(b); // 2
console.log(args) // [3, 4, 5, 6, 6]
1번 경우랑 비슷하다. 엮으로 뒤에 오는 값들은 오히려 필요 없을 때 이렇게 무시하면 된다.
function f() {
return [1,2,3,4,5,6,6,];
}
const [a, b] = f();
console.log(a); // 1
console.log(b); // 2
응용해서 나머지는 다 묶어보기
function f() {
return [1,2,3,4,5,6,6,];
}
const [a, ...b] = f();
console.log(a); // 1
console.log(b); //[2,3,4,5,6,6]
여기서 부터 혼돈이 온다,,,
const key = {p: 42, q: true};
const {p: foo, q: bar} = key;
}
console.log(foo); // 42
console.log(bar); // true
p와 q를 기준으로 덮었는데 foo, bar값이 변하지 않고, foo => 42 bar => true가 된다.
이부분은 아직 이해가 부족하지만,, 그렇구나! 하고 넘어갔다..
(이해안되는 부분은 console로 출력후, 이렇게 나오는구나!! 하고 그냥 믿는편..)
헷갈리는 응용
const {a = 10, b = 5} = {a: 3};
console.log(a); // 3
console.log(b); // 5
처음보고 생각한 풀이
a = 10, b =5를 넣고 => {a:10, b=5}
=> {a:3} 대입하면???
=> console.log(10) =>> 3 ????
먼가 잘못된걸 느끼고, 위에 객체할당이랑 차이점을 비교해보니,
아!! 위에는 변수가 이름이 있구나 이름으로 선언했구나!!
--> foo, bar ?????
다시 생각해보면 위의 예제는 key,value의 property형식인데, 그 아래의 예제는 변수 a,b에 직접값을 할당해준것이다.
지금까지 해본거 응용 해보기
const hardobj = {
title: "어려운 오브젝트 객체 할당",
translations: [
{
locale: "de",
localization_tags: [ ],
last_edit: "2014-04-14T08:43:37",
url: "/de/docs/Tools어려운 오브젝트 객체 할당",
title: "구조 분해 할당"
}
],
url: "/en-US/docs/Tools어려운 오브젝트 객체 할당"
};
const { title: englishTitle, translations: [{ title: localeTitle }] } = hardobj;
console.log(englishTitle); // "어려운 오브젝트 객체 할당"
console.log(localeTitle); // "구조 분해 할당"
여기까지 구조 분해 할당을 직접 해보았다..
구분할조해당 헷갈지리않고 잘 쓸 수 있을 것 같아요!