View

Object destructuring -2

special 2021. 8. 14. 00:16

앞서 다루었던 restaurant 이름의 object에 

orderDelivery라는 이름의 속성을  추가하여 살펴보자!😊

 

orderDelivery: function(obj) {
	console.log(obj);
}, };

하나의 argument를 전달받을 수 있는 function

 

restaurant.orderDelivery({

time: '22:30',

address: 'Address',

mainIndex: 2,

starterIndex: 2,

}); // 하나의 object를 argument로 전달한 것이다.

 

이를 참고로 위의 orderDelivery를 아래와 같이 수정해보자

orderDelivery: function({
	starterIndex,
    mainIndex,
    time,
    address
}){
	console.log(`Order received! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]} will be delivered to ${address} at ${time}!`);
},

이과 같이 수정해도, orderDelivery는 하나의argument를 전달 받는 것이다.

 

restaurant.orderDelivery({

time: '22:30',

address: 'Address',

mainIndex: 2,

starterIndex: 2,

}); 

다시 실행해보면,

Order received! Garlic Bread and Risotto will be delivered to Via del Sole, 21 at 22:30 

가 콘솔에 출력되는 것을 확인 할 수 있다.

 

restaurant.orderDelivery에서 전달해준 object순서와 function({내부}) 내부에 정의된 순서는 중요하지 않다.

object는 순서가 없으므로 정확한 이름으로 작성해주면 된다.

 

 

만약 time, address, mainIndex, starterIndex중 어떤 값을 전달해 주지 않는다면

해당 부분은 undefined로 출력되게 된다.

이 경우에도 초기값을 지정해 줄 수 있다.

 

orderDelivery: function() 부분을 아래와 같이 수정해 준다.

orderDelivery: function({
	starterIndex = 1,
    mainIndex = 0,
    time = '20:00',
    address,
}){}

위와 같이 수정해주면 starterIndex와 mainIndex, time에 초기값이 지정되었다.

 

restaurant.orderDelivery({

address: '주소',

starterIndex: 1,

});

을 실행하면

 

콘솔에 아래와 같이 출력되는 것을 확인할 수 있다.

Order received! Bruschetta and Pizza will be deliverd 주소 at 20:00

Share Link
reply
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28