JavaScript/배열

[JavaScript]배열 구조 분해(Array Destructuring)

DevStory 2022. 9. 20.

배열 구조 분해(Array Destructuring)

Destructuring이라는 단어는 무언가를 파괴 또는 축소하는 것을 의미합니다.

 

JavaScript의 구조 분해는 배열이나 객체에 할당된 데이터에서 특정 값 또는 여러 값을 추출하는 방법입니다. 

 

배열의 요소를 가져오는 일반적인 방법은 대괄호 표기법을 사용하여 인덱스로 접근하는 것입니다.

const strArray = ['One', 'Two', 'Three'];
const strOne = strArray[0];
const strTwo = strArray[1];
const strThree = strArray[2];

console.log(strOne);   // One
console.log(strTwo);   // Two
console.log(strThree); // Three

 

구조 분해를 사용하면, 다음 소스 코드처럼 대괄호를 사용하여 3개의 변수를 선언과 동시에 배열의 값을 가져올 수 있습니다.

const strArray = ['One', 'Two', 'Three'];
const [strOne, strTwo, strThree] = strArray;

console.log(strOne);   // One
console.log(strTwo);   // Two
console.log(strThree); // Three

구조 분해를 사용할 때, 대괄호를 사용하므로 마치 배열을 선언하는 것처럼 보일 수 있지만, 실제로 배열을 생성하지는 않습니다.

 

배열 strArray의 첫 번째 요소인 'One'이 변수 strOne에 할당되고 두 번째 요소인 'Two'가 변수 strTwo에 할당되고 마지막 요소인 'Three'가 변수 strThree에 할당됩니다.

 

구조 분해를 사용하면, 일반적인 방법으로 배열의 요소를 가져오는 것보다 소스 코드가 간결화됩니다.

 

이제, 구조 분해에 대한 개념 설명이 끝났으므로 배열에서 구조 분해를 응용할 수 있는 몇 가지 예제를 설명합니다.


응용 1. 나머지 연산자

배열 구조 분해에서 나머지 연산자(...)를 사용하면, 배열의 나머지 모든 요소를 나머지 연산자를 사용한 변수에 할당할 수 있습니다.

const strArray = ['One', 'Two', 'Three', 'Four', 'Five'];
const [strOne, strTwo, ...args] = strArray;

console.log(strOne); // One
console.log(strTwo); // Two
console.log(args);   // ['Three', 'Four', 'Five']

 

참고로 나머지 연산자는 무조건 마지막 위치에 존재해야 합니다. 만약, 다음 예제처럼 중간에 나머지 연산자를 사용한 경우 SyntaxError가 발생합니다.

const strArray = ['One', 'Two', 'Three', 'Four', 'Five'];

// Uncaught SyntaxError: Rest element must be last element
const [firstElement, ...args, lastElement] = strArray;

응용 2. 요소 건너뛰기

5개의 요소를 가진 배열에서 1, 3, 5번째 요소만 가져오려고 한다면, 다음 예제처럼 쉼표에 변수 이름을 작성하지 않고 건너뜁니다.

const strArray = ['One', 'Two', 'Three', 'Four', 'Five'];
const [strOne, , strThree, , strFive] = strArray;

console.log(strOne);   // One
console.log(strThree); // Three
console.log(strFive);  // Five

응용 3. 기본 값 설정

0개의 요소를 가진 빈 배열에서 1, 2, 3번째 요소를 구조 분해로 가져오는 경우 변수에 undefined가 할당됩니다.

const strArray = [];
const [strOne, strTwo, strThree] = strArray;

console.log(strOne);   // undefined
console.log(strTwo);   // undefined
console.log(strThree); // undefined

 

배열에 특정 위치의 요소가 존재하지 않거나 undefined가 아닌 기본 값을 설정하고 싶은 경우 다음 예제처럼 변수에 기본 값을 할당할 수 있습니다.

const strArray = [undefined];
const [strOne = 'One', strTwo = 'Two', strThree] = strArray;

console.log(strOne);   // One
console.log(strTwo);   // Two
console.log(strThree); // undefined

배열 strArray에 세 번째 요소가 존재하지 않으며, 변수 strThree에 기본 값을 설정하지 않았으므로 변수 strThree에는 undefined가 할당됩니다.


응용 4. 값을 교환

두 변수의 값을 교환해야 하는 경우 일반적으로 임시 변수를 사용하지만, 구조 분해를 사용한다면, 임시 변수를 사용하지 않고 두 변수의 값을 쉽게 교환할 수 있습니다.

let first = 'Hello', second = 'JavaScript';
[first, second] = [second, first];

console.log(first);  // JavaScript
console.log(second); // Hello

정리

  • 배열의 구조 분해는 인덱스를 직접 명시하지 않아도 배열의 요소를 변수에 할당할 수 있는 기능입니다.
  • ES6 2015를 지원하지 않는 브라우저는 구조 분해를 지원하지 않을 수 있습니다.
반응형

댓글