[JS] 16. 응용: 비 구조화 할당 / spread 연산자
1) 비 구조화 할당
비 구조화 할당(구조 분해 할당):
배열의 요소들 또는 객체의 프로퍼티 값들을 변수에 할당받아 사용하는 방법.
① 배열의 비 구조화 할당
배열의 비 구조화 할당은 대괄호를 이용하여 배열의 요소들을 인덱스 순서대로 변수에 할당합니다.
let arr = [1, 2, 3];
let one = arr[0];
let two = arr[1];
let three = arr[2];
console.log(one, two, three); //1,2,3
⇓
let arr = [1, 2, 3];
let [one, two, three,four] = arr; //배열 arr의 요소를 인덱스 순서대로 각각 변수 one, two, three에 할당
console.log(one, two, three,four); //1,2,3, undefined
* 배열의 선언 분리 비 구조화 할당
let [one, two, three, four] = [1, 2, 3];
//배열 arr의 요소를 인덱스 순서대로 각각 변수 one, two, three에 할당
console.log(one, two, three, four); //1,2,3, undefined
[기본값 설정]
위 코드에서 변수 four는 배열에서 대응하는 값이 없어 undefined 값을 가지게 됩니다.
이처럼 비 구조화 할당에서 변수가 값을 할당받지 못한 경우에 해당 변수는 undefined 값을 가집니다.
변수가 값을 할당받지 않았을 때 undefined가 아닌 다른 값을 가지도록 하기위해 기본값을 설정할 수 있습니다.
let [one, two, three, four = 4] = [1, 2, 3];
console.log(one, two, three, four); //1,2,3,4
[데이터 스왑 활용]
* 스왑(swap): 변수의 값을 교환하는 것.
배열의 비 구조화 할당을 활용하여 값을 임시로 저장하는 변수를 생성하지 않고 두 값을 스왑할 수 있습니다.
let a = 10;
let b = 20;
[a,b] = [b,a];
console.log(a,b); //20, 10
② 객체의 비 구조화 할당
객체의 비 구조화 할당은 중괄호를 이용하여 객체의 프로퍼티 vlaue 값들을 순서와 상관없이 key 값을 기준으로 변수에 할당합니다.
let object = { one: 1, two: 2, three: 3 };
let { three, one, two, four } = object;
console.log(one, two, three, four); //1,2,3, undefined
key 값을 기준으로 할당하기 때문에 변수의 이름은 key 값과 동일해야 한다는 제약이 있습니다.
하지만 변수의 이름을 다음과 같이 key 값과 다르게 설정하는 것도 가능합니다.
let object = { one: 1, two: 2, three: 3 };
let { three: num3, one, two, four } = object;
console.log(one, two, num3, four); //1,2,3, undefined
[기본값 설정]
배열의 비 구조화 할당과 마찬가지로 변수가 값을 할당받지 못한 경우에 해당 변수는 undefined 값을 가지게 되고, 다른 값을 가지도록 하기 위해 기본값을 설정할 수 있습니다.
let object = { one: 1, two: 2, three: 3 };
let { three, one, two, four = 4 } = object;
console.log(one, two, three, four); //1,2,3,4
2) spread 연산자
spread 연산자: '...' (온점 세 개)로 표기하며 어떤 객체의 프로퍼티들을 다른 객체에 펼쳐주거나 어떤 배열의 원소를 다른 배열에 펼쳐주는 역할을 합니다.
① 객체에서의 spread
객체에서 spread 연산자는 공통된 프로퍼티를 중복해서 작성해야 할 때 사용합니다.
const cookie = {
base: "cookie",
madeIn: "korea"
};
const chocochipCookie = {
base: "cookie",
madeIn: "korea",
toping: "chocochip"
};
const blueberryCookie = {
base: "cookie",
madeIn: "korea",
toping: "blueberry"
};
위 코드를 보면 객체들의 공통된 프로퍼티 base와 madeIn이 중복해서 작성되어 있습니다.
⇓
const cookie = {
base: "cookie",
madeIn: "korea"
};
const chocochipCookie = {
...cookie,
toping: "chocochip"
};
const blueberryCookie = {
...cookie,
toping: "blueberry"
};
② 배열에서의 spread
const noTopingCookies = ["촉촉한 쿠키", "안 촉촉한 쿠키"];
const topingCookies = ["초코칩 쿠키", "블루베리 쿠키", "아몬드 쿠키"];
const allCookies = [...noTopingCookies, ...topingCookies];
console.log(allCookies);
위 예시 코드에서는 두 배열을 하나의 배열로 합쳐주고 있습니다.
이때 concat 함수를 사용해도 되지만 spread 연산자를 이용하면 concat과 달리 이어 붙일 배열들 외에 추가적으로 새로운 요소를 유연하게 넣어줄 수 있습니다.
const noTopingCookies = ["촉촉한 쿠키", "안 촉촉한 쿠키"];
const topingCookies = ["초코칩 쿠키", "블루베리 쿠키", "아몬드 쿠키"];
const allCookies = [...noTopingCookies, ...topingCookies, "시그니처 쿠키"];
console.log(allCookies);