프론트엔드✏️/코드캠프

구조 분해 할당(Destructuring Assignment)

당근먹는하니 2022. 5. 23. 01:54
728x90
반응형

  구조 분해 할당

 배열의 값이나 객체의 속성을 별개의 변수로 풀 수 있게 해주는 자바스크립트 표현식

 

let a, b, rest;
[a, b] = [10, 20];

console.log(a);
// expected output: 10

console.log(b);
// expected output: 20

[a, b, ...rest] = [10, 20, 30, 40, 50];

console.log(rest);
// expected output: Array [30,40,50]


// 출처 : developer.mozilla.org - destructuring assignment

😶rest? 

 rest 엘리먼트는 배열의 맨 뒤에 쓸 수 있는데, ...rest 라고 쓰면 그 나머지 값이 rest에 담기게 된다. 

 

 

const x = [1, 2, 3, 4, 5];
const [y, z] = x;      // 이
console.log(y); // 1    // 부
console.log(z); //2     // 분


// 출처 : mdn - 구조 분해 할당

The destructuring assignment uses similar syntax, but on the left-hand side of the assignment to define what values to unpack from the sourced variable.

구조 분해 할당의 구문은 const x = [1, 2, 3, 4, 5]와 비슷하지만, 대신 할당문의 좌변에서 사용하고 원래 변수에서 어떤 값을 분해해 할당할지 정의한다. 

 

말 그대로 원래 있는 구조를 분해해서 할당한다. 오른쪽에 있는 애를 쪼개어 왼쪽에 할당한다!

 

 

let banana = "yellow";
let kiwi = "green";

[banana, kiwi] = [kiwi, banana];
console.log(kiwi);  // "yellow"
console.log(banana); // "green"

 

구조 분해 할당을 이용해서 swap 없이 두 변수의 값을 교환할 수도 있다.

 

function sayHi() {
	return ["H", "i"];
}

let a, b;
[a, b] = sayHi();
console.log(a); // "H"
console.log(b); // "i"

함수가 반환하는 값을 바로 변수에 담을 수도 있다.

 

 

 

~~~ 보충 예정

728x90
반응형