티스토리 뷰
5.10 Destructuring assignment
Array destructuring|
// we have an array with a name and surname
let arr = ["John", "Smith"]
// destructuring assignment
// sets firstName = arr[0]
// and surname = arr[1]
let [firstName, surname] = arr;
alert(firstName); // John
alert(surname); // Smith
// --------------------------
let [firstName, surname] = "John Smith".split(' ');
alert(firstName); // John
alert(surname); // Smith
분해 중, 버리고 싶은 요소는 콤마를 사용해서 버릴 수 있다.
// second element is not needed
let [firstName, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
alert( title ); // Consul
destructuring assignment는 등호 오른쪽의 값을 iterating 하면서 이루어지기 때문에, 아래와 같은 예시가 가능하다.
let [a, b, c] = "abc"; // ["a", "b", "c"]
let [one, two, three] = new Set([1, 2, 3]);
여러가지 예시들...
let user = {};
[user.name, user.surname] = "John Smith".split(' ');
alert(user.name); // John
alert(user.surname); // Smith
// ------------------------
let user = {
name: "John",
age: 30
};
// loop over the keys-and-values
for (let [key, value] of Object.entries(user)) {
alert(`${key}:${value}`); // name:John, then age:30
}
// ------------------------
let guest = "Jane";
let admin = "Pete";
// Let's swap the values: make guest=Pete, admin=Jane
[guest, admin] = [admin, guest];
alert(`${guest} ${admin}`); // Pete Jane (successfully swapped!)
the rest '...'
우항의 리스트보다 좌항의 배열이 훨씬 짧을 경우 추가적인 요소는 무시한다. 추가적인 요소도 같이 저장하고 싶다면 '...rest' 구문을 활용한다.
let [name1, name2] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
alert(name1); // Julius
alert(name2); // Caesar
// Further items aren't assigned anywhere
// --------------------------
let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
// rest is an array of items, starting from the 3rd one
alert(rest[0]); // Consul
alert(rest[1]); // of the Roman Republic
alert(rest.length); // 2
default values
반대로 우항이 좌항보다 작은 크기일 경우 undefined로 할당된다.
let [firstName, surname] = [];
alert(firstName); // undefined
alert(surname); // undefined
아래처럼 default 값을 설정해 줄 수도 있겠다. 또한, 사용자로부터 입력을 받아서 할당해줄수도 있다.
// default values
let [name = "Guest", surname = "Anonymous"] = ["Julius"];
alert(name); // Julius (from array)
alert(surname); // Anonymous (default used)
// -----------------
// runs only prompt for surname
let [name = prompt('name?'), surname = prompt('surname?')] = ["Julius"];
alert(name); // Julius (from array)
alert(surname); // whatever prompt gets
Object destructuring
객체의 경우도 배열이랑 비슷한 방식으로 순서대로 변수를 할당하게 된다.
let options = {
title: "Menu",
width: 100,
height: 200
};
let {title, width, height} = options;
alert(title); // Menu
alert(width); // 100
alert(height); // 200
물론, 아래와 같이 변수를 따로 할당해 줄수도 있다.
// changed the order in let {...}
let {height, width, title} = { title: "Menu", height: 200, width: 100 }
// ------------------
let options = {
title: "Menu",
width: 100,
height: 200
};
// { sourceProperty: targetVariable }
let {width: w, height: h, title} = options;
// width -> w
// height -> h
// title -> title
alert(title); // Menu
alert(w); // 100
alert(h); // 200
Nested destructuring
let options = {
size: {
width: 100,
height: 200
},
items: ["Cake", "Donut"],
extra: true
};
// destructuring assignment split in multiple lines for clarity
let {
size: { // put size here
width,
height
},
items: [item1, item2], // assign items here
title = "Menu" // not present in the object (default value is used)
} = options;
alert(title); // Menu
alert(width); // 100
alert(height); // 200
alert(item1); // Cake
alert(item2); // Donut
Smart function parameters
이해가 잘안된다...
'스터디 > JavaScript' 카테고리의 다른 글
모던 자바스크립트 튜토리얼 part1 - 5.12 (0) | 2024.05.21 |
---|---|
모던 자바스크립트 튜토리얼 part1 - 5.11 (0) | 2024.05.21 |
모던 자바스크립트 튜토리얼 part1 - 5.9 (0) | 2024.05.21 |
모던 자바스크립트 튜토리얼 part1 - 5.7 ~ 8 (0) | 2024.05.21 |
모던 자바스크립트 튜토리얼 part1 - 5.6 (0) | 2024.05.20 |
댓글