javascript
[Javascript] 비구조화 할당
dyyoo
2019. 11. 22. 01:09
객체, 배열로부터 속성이나 요소를 쉽게 꺼낼수 있다.
node는 모듈을 사용하므로 이런 방식을 자주 사용하다.
기존의 방법
let candyMachine = {
status: {
name: 'node',
count: 5,
},
getCandy: function() {
this.status.count--;
return this.status.count;
}
};
let getCandy = candyMachine.getCandy;
let count = candyMachine.status.count;
새로운 방법
let candyMachine = {
status: {
name: 'node',
count: 5,
},
getCandy() {
this.status.count--;
return this.status.count;
}
};
const { getCandy, status: {count} } = candyMachine;
candyMachine 객체 안의 속성을 찾아서 변수와 매칭해준다.
count처럼 여러 단계 안의 속성도 찾을 수 있다.
배열도 비구조화 할 수 있다.
let array = ['nodejs', {}, 10, true];
let node = array[0];
let obj = array[1];
let bool = array[3];
//위의 3라인을 아래로 바꿀수 있다.
let [node1, obj1, , bool1] = array;
console.log(node1, obj1, bool1);