자바스크립트 JS - 구조분해 할당

hyunnu·2021년 7월 20일
0
post-thumbnail

구조분해 할당

const example = { a: 123, b: { c: 135, d: 146 } }
const a = example.a;
const d = example.b.d;

구조분해 할당
=> const { a, b: { d } } = example;
console.log(a); //123
console.log(d); //146

객체는 key가 똑같아야 함

배열 구조분해 할당

arr = [1,2,3,4,5]
const x = arr[0];
const y = arr[1];
const z = arr[4];

구조분해 할당
=> const [x,y,,,z] = arr; //3,4번째는 변수대입 x

배열은 자리가 똑같아야 함

this 구조분해 할당 x

var candyMachine = {
	status: {
    	name: 'node',
      	count: 5,
    },
  	getCandy: function () {
    	this.status.count--;
      	return this.status.count;
    },
};
var getCandy = candyMachine.getCandy;
var count = candyMachine.status.count;

var getCandy와 var count에 주목
candyMachine부터 시작해서 속성을 찾아 들어가야 함

var candyMachine = {
	status: {
    	name: 'node',
      	count: 5,
    },
  	getCandy() {
    	this.status.count--;
      	return this.status.count;
    },
};
const { getCandy, status: { count } } = candyMachine;
  • const { 변수 } = 객체; 로 객체 안의 속성을 변수명으로 사용 가능
    (단, getCandy()를 실행했을 때 결과가 candyMachine.getCandy()와는 달라지므로 주의
  • const처럼 속성 안의 변수명으로 사용 가능
profile
Data Engineer / Back-End Developer

0개의 댓글