본문 바로가기
JavaScript

[JavaScript] 옵셔널체이닝

by 박헹구 2022. 3. 26.
반응형
const weekdays = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
const openingHours = {
  [weekdays[3]]: {
    open: 12,
    close: 22,
  },
  [weekdays[4]]: {
    open: 11,
    close: 23,
  },
  [weekdays[5]]: {
    open: 0, // Open 24 hours
    close: 24,
  },
};

...

if(restaurant.openingHours && restaurant.openingHours.mon)
  console.log(restaurant.openingHours.mon.open);

//옵셔널체이닝 사용
console.log(restaurant.openingHours.fri?.open);

//값이 있으면 해당값 금요일의 오픈시간은 11시니까 11 , 값이 없으면 undefined로 나온다.
const days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];

for(const day of days) {
  // console.log(day);
   const open = restaurant.openingHours[day]?.open ?? 'Closed';
  console.log(`On ${day}, we open at ${open}`);
}

//Methods
console.log(restaurant.order?.(0,1) ?? 'Method does not exist');

//Arrays
const users = [
  {name: 'Hyemgu', email: 'hyemgu@gmail.com'}
];
console.log(users[0]?.name ?? 'User array empty');

if(users.length >0) console.log(users[0].name); else console.log('user array empty')

 

반응형

댓글