ES6 destructuring
배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식으로,
쉽게 데이터 뭉치를 만들 수 있다.
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a); // 10
console.log(b); // 20
console.log(rest); // [30, 40, 50]
// Stage 4(finished) proposal
({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
console.log(a); // 10
console.log(b); // 20
console.log(rest); // {c: 30, d: 40}
배열 구조 분해
기본 변수 할당
var foo = ["one", "two", "three"];
var [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"
선언에서 분리한 할당
변수의 선언이 분리되어도 구조 분해를 통해 값을 할당할 수 있다.
var a, b;
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
변수 값 교환하기
하나의 구조 분해 표현식만으로 두 변수의 값을 교환할 수 있다. (임시변수를 사용하지 않고 값교환이 가능함)
var a = 1;
var b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1
함수가 반환한 배열 분석
function f() {
return [1, 2];
}
var a, b;
[a, b] = f();
console.log(a); // 1
console.log(b); // 2
구조 분해를 사용하면 반환된 배열에 대한 작업을 더 간결하게 수행할 수 있다.
일부 반환 값 무시하기
function f() {
return [1, 2, 3];
}
var [a, , b] = f();
console.log(a); // 1
console.log(b); // 3
변수에 배열의 나머지를 할당하기
분해하고 남은 부분을 하나의 변수에 할당할 수 있다.
var [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]
https://mariusschulz.com/blog/destructuring-regular-expression-matches-in-ecmascript-2015
Destructuring Regular Expression Matches in ECMAScript 2015
Destructuring assignments work perfectly together with regular expression matches as returned by the exec function. Pattern matching helps assign matches and captures to local variables.
mariusschulz.com
정규 표현식과 일치하는 값 해체하기
정규 표현식의 exec() 메서드는 일치하는 부분를 찾으면 그 문자열에서 정규식과 일치하는 부분 전체를 배열의 맨 앞에 반환하고, 그 뒤에 정규식에서 괄호로 묶인 각 그룹과 일치하는 부분을 포함하는 배열을 반환한다. 구조 분해 할당은 필요하지 않은 경우 일치하는 전체 부분은 무시하고 필요한 부분만 쉽게 빼올 수 있다.
function parseProtocol(url) {
var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
if (!parsedURL) {
return false;
}
console.log(parsedURL); // ["https://developer.mozilla.org/en-US/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"]
var [, protocol, fullhost, fullpath] = parsedURL;
return protocol;
}
console.log(parseProtocol('https://developer.mozilla.org/en-US/Web/JavaScript')); // "https"
객체 구조 분해
기본 할당
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true
선언 없는 할당
변수의 선언과 분리하여 변수에 값을 할당할 수 있다.
var a, b;
({a, b} = {a: 1, b: 2});
var {a, b} = {a:1, b:2} // ({a, b} = {a: 1, b: 2}) 와 같다.
새로운 변수 이름으로 할당하기
객체로부터 속성을 해체하여 객체의 원래 속성명과는 다른 이름의 변수에 할당할 수 있습니다.
var o = {p: 42, q: true};
var {p: foo, q: bar} = o;
console.log(foo); // 42
console.log(bar); // true
기본값 갖는 새로운 이름의 변수에 할당하기
새로운 변수명 할당과 기본값 할당을 한번에 할 수 있습니다.
var {a: aa = 10, b: bb = 5} = {a: 3};
console.log(aa); // 3
console.log(bb); // 5
중첩된 객체 및 배열의 구조 분해
var metadata = {
title: "Scratchpad",
translations: [
{
locale: "kr",
localization_tags: [ ],
last_edit: "2023-09-14T08:43:37",
url: "/kr/docs/Tools/Scratchpad",
title: "JavaScript-Umgebung"
}
],
url: "/en-US/docs/Tools/Scratchpad"
};
var { title: englishTitle, translations: [{ title: localeTitle }] } = metadata;
console.log(englishTitle); // "Scratchpad"
console.log(localeTitle); // "JavaScript-Umgebung"
for of 반복문과 구조 분해
var people = [
{
name: "Mike Tyson",
family: {
mother: "Jane Tyson",
father: "Harry Tyson",
sister: "Samantha Tyson"
},
age: 35
},
{
name: "Tom Jones",
family: {
mother: "Norah Jones",
father: "Richard Jones",
brother: "Howard Jones"
},
age: 25
}
];
for (var {name: n, family: { father: f } } of people) {
console.log("Name: " + n + ", Father: " + f);
}
// "Name: Mike Tyson, Father: Harry Tyson"
// "Name: Tom Jones, Father: Richard Jones"
함수 매개변수로 전달된 객체에서 필드 해체하기
user 객체로부터 id, displayName 및 firstName 을 해체해 출력합니다.
function userId({id}) {
return id;
}
function whois({displayName: displayName, fullName: {firstName: name}}){
console.log(displayName + " is " + name);
}
var user = {
id: 42,
displayName: "jdoe",
fullName: {
firstName: "John",
lastName: "Doe"
}
};
console.log("userId: " + userId(user)); // "userId: 42"
whois(user); // "jdoe is John"
객체 구조 분해에서 Rest
구조 분해에 rest 구문을 추가하고 있습니다. rest 속성은 구조 분해 패턴으로 걸러지지 않은 열거형 속성의 키를 가진 나머지 항목들을 모음.
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
a; // 10
b; // 20
rest; // { c: 30, d: 40 }