const object = {
a: 1,
b: 2,
c: 3,
d: 4,
}
const {a, b, ...rest} = object
// a 1
// b 2
// rest = {c: 3, d: 4}
const object1 = {
a: 1
}
const {a1: first} = object1
// first: 1
- 객체 내부 이름으로 꺼내오며 새로운 이름으로 다시 할당하는 것 가능.
/* Example 1 */
const object = {
a: 1, b: 1
}
const {a=10, b=10, c=10} = object
// a 1
// b 1
// c 10
/* Example 2 */
function Sample({a, b}) {
return a + b
}
Sample({a: 3, b: 5})
//8
/* Example 3 */
const key = 'a'
const {[key]: a} = object
// a = 1
/* Example 4 */
const {[key]} = object
// Uncaught SyntaxError: unexpected token '['
- Example1 처럼 기본값을 주는 것 가능하며, Example2 처럼 변수에 있는 값으로 꺼내오는 계산된 속성이름 방식도 가능하다. Example3 처럼 [key] 문법을 사용하여 object안의 'a'값을 꺼내오며, 계산된 속성 이름을 계산된 이름인 [key]로 값을 꺼내고 어떤 변수명으로 할당해야 할지 모르기 때문이다.
const object = {
a:1,
b:2,
c:3,
d:4,
}
const {a, ...rest} = object
// rest {b:2,c:3,d:4}
const {a, b, ...rest} = object
// rest {c:3,d:4}
- 전개 연산자 '...'을 사용하면 나머지 값을 가져올 수 있으며, 전개 연산자는 순서가 중요함.
/* before transpile */
const object = {a:1, b:2, c:3}
const {a, ...rest} = object
/* after transpile */
function _objectWithoutProperties(source, exclude) {
if(source == null) return
var target = _objectWithoutPropertiesLoose(source, exclude)
var key, i
if(Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source)
for(i = 0; i < sourceSymbolsKeys.length; i++) {
key = sourceSymbolKeys[i]
if(exclude.indexOf(key) >= 0) continue
if(!Object.propertyIsEnumerable.call(source, key)) continue
target[key] = source[key]
}
}
return target
}
function _objectWithoutPropertiesLoose(source, exclude) {
if(source == null) return {}
var target = {}
var sourceKeys = Object.keys(source)
var key, i
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i]
if(exclude.indexOf(key) >= 0) continue
target[key] = source[key]
}
return target
}
var object = {a:1, b:2, c:3}
var a = object.a,
rest = _objectWithoutProperties(object, ['a'])
-_objectWithoutPropertiesLoose 함수에서 객체와 해당 객체에서 제외할 키가 포함된 배열 두 가지를 인수로 받으며, 두 가지 값을 활용해서 해당 객체에서 특정키를 제외. _objectWithoutProperties 함수에서는 Object.getOwnPropertySymbols가 (내부에서 symbols) 존재하는 경우를 대비해 이에 대한 예외 처리를 추가함.
- transpile 후 번들링 크기가 상대적으로 커지기 때문에 개발하는 환경이 ES5를 고려해야 하고, 객체 구조 분해 할당을 자주 쓰지 않는다면 꼭 써야 할지를 생각해봐야 함. 전개 연산자만 필요하다면 외부라이브러리인 'lodash.omit', 'ramda.omit' 등을 고려해 볼 필요가 있다.
| AST(Abstract Syntax Tree, 추상 구문 트리) (4) | 2024.09.25 |
|---|---|
| 자바스크립트 interpreter/compiler pipeline (2) | 2024.09.25 |
| 배열 구조 분해 할당 (0) | 2024.09.23 |
| 브라우저에 따른 고려사항과 compile, transpile, interpreter (0) | 2024.09.21 |
| (4) 태스크 큐(task queue) 와 마이크로 태스크 큐(micro task queue) (2) | 2024.09.20 |