Node.js/JavaScript

[키워드 정리] 자바스크립트에서 '구조분해'란 무엇인가

왈왈디 2023. 4. 1. 22:11
728x90

JavaScript에서 '구조 분해(destructuring)'객체배열에서 필요한 값을 추출하여 변수에 할당하는 것을 말한다.

이를 통해 코드를 간결하고 가독성이 좋게 작성할 수 있다.

 

객체 구조 분해

객체 구조 분해는 객체에서 필요한 값을 중괄호({}) 안에 변수명으로 선언하면 된다.

const person = { name: "John", age: 30, city: "New York" };

const { name, age } = person;

console.log(name); // 출력값: "John"
console.log(age); // 출력값: 30

위 예시에서는 person 객체에서 name과 age 프로퍼티 값을 추출하여 변수에 할당했다.

이후에는 name과 age 변수를 사용하여 다른 코드에서 값을 참조할 수 있다.


배열 구조 분해

배열 구조 분해는 배열에서 필요한 값을 대괄호([]) 안에 변수명으로 선언하면 된다.

const numbers = [1, 2, 3];

const [first, second] = numbers;

console.log(first); // 출력값: 1
console.log(second); // 출력값: 2

위 예시에서는 numbers 배열에서 첫 번째와 두 번째 값을 추출하여 first와 second 변수에 할당했다.

이후에는 first와 second 변수를 사용하여 다른 코드에서 값을 참조할 수 있다.

 

배열 구조 분해에서 특정 값을 무시하기 위해서는, 해당 요소 차례를 공백으로 두고 ','를 입력하면 된다.

function f() {
  return [1, 2, 3];
}

var [a, , b] = f();
console.log(a); // 1
console.log(b); // 3

 

배열 구조 분해에서는 앞 요소들을 변수에 할당하고, 나머지를 전부 하나의 변수에 배열로 할당할 수 있다.

var [a, b, c, ...d] = [1, 2, 3, 4, 5, 6];
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
console.log(d); // [4, 5, 6]

객체와 배열에서 동시에 값 추출이 가능하며, 이때는 중괄호와 대괄호를 조합하여 사용한다.

const person = { name: "John", age: 30, city: "New York" };
const numbers = [1, 2, 3];

const { name, age } = person;
const [first, second] = numbers;

console.log(name); // 출력값: "John"
console.log(age); // 출력값: 30
console.log(first); // 출력값: 1
console.log(second); // 출력값: 2

예시에서는 객체 person에서 name age 값을, 배열 numbers에서 번째와 번째 값을 구조 분해하여 변수에 할당했다.

728x90