피리부는 사나이 (pied piper)

[JS] 비 구조화 할당 / Spread 연산 본문

Java Script

[JS] 비 구조화 할당 / Spread 연산

코더 451 2022. 4. 28. 10:49

배열의 비 구조화 할당

 

변수에 배열 요소 (인덱스)를 하나하나 할당하는 것을 간단화 시킬 수 있음
 
let arr = ["one", "two", "three"];


//1. 기존의 방식 

let one = arr[0];
let two = arr[1];
let three = arr[2];

console.log(one, two, three);


//2. 더 나은 방식 



let [one, two, three] = arr;
//배열안에 변수 할당 후 오른 쪽에 배열 할당하면 인덱스 순서대로 부여

//대괄호를 이용해서 배열을 변수에 할당하는 것은 비 구조화 할당이라고 함

 

 

객체의 비 구조화 할당

객체 프로퍼티 요소를 변수에 하나하나 ‘표기법'으로 할당하는 것을 간단화 시킬 수 있음
//기존 방식 


let object = { one: "one", two: "two", three: "three"};

let one = object["one"];
let two = object.two;
let three = object.three;

//반복노동 존재, 번거로움

console.log(one, two, three);

// 객체의 비 구조화 할당 

let object = { one: "one", two: "two", three: "three"};

let { one, two, three } = object;
console.log(one, two, three);

//훨씬 간결함, 인덱스 (순서)가 아니라 '키'값을 기준으로 비구조화 할당이
// 이루어짐



//변수의 이름을 바꿔서 할당도 가능 

let { name : myName, one: oneONe, two, three, abc = "four"} = object;

 

 

 


Spread 연산자

: 객체의 값을 새로운 객체에 펼쳐주는 역할을 하는 연산자

 

const cookie = {
base: "cookie",
madeIn: "korea";

};

const appleCookie = {
...cookie,
toping: "apple"
};

const blueberryCookie = {
...cookie,
toping: "blueberry"
};


const chocolateCookie = {
...cookie,
toping: "chocolate"
};

console.log(appleCookie);
console.log(blueberryCookie);
console.log(chocolateCookie);

//결과 

//cookie 객체에있는 프로퍼티 2개의 키와 밸류가 그대로 
//복사 됨

 

배열에도 사용가능 하다. (배열 합치는 concat와 같음)

 

const noTopingCookies = ["촉촉한쿠키", "안촉촉한 쿠키"];
const topingCookies = ["바나나쿠키", "블루베리쿠키", "딸기쿠키",
"초코칩쿠키"];

const allCookies = [...noTopingCookies, ...topingCookies];

console.log(allCookies);

//나뉘어있던 두 가지 배열의 5개의 요소가 
//allCookies로 모두 합쳐진다.

 

Comments