typescript 当输入参数为数组时,如何减少if语句?

jaxagkaj  于 2023-01-06  发布在  TypeScript
关注(0)|答案(1)|浏览(93)

我有一个任务要做,我有一个数组的天。我将不得不打印,如果数组包括特定的天。数组可以有任何天在它的用户将决定他们想打印的天。

callDays(){
   
        const days: string[]=['Sunday','Monday','Wednesday','Thursday','Friday','Saturday'];
        if(days.includes('Sunday')){
        console.log('Sunday is included');
        }
        if(days.includes('Monday')){
        console.log('Monday is included');
        }
        if(days.includes('Tuesday')){
        console.log('Tuesday is included');
        }
        if(days.includes('Wednesday')){
        console.log('Wednesday is included');
        }
        if(days.includes('Thursday')){
        console.log('Thursday is included');
        }
        if(days.includes('Friday')){
        console.log('Friday is included');
        }
        if(days.includes('Saturday')){
        console.log('Saturday is included');
        }
     }

在上面的例子中,星期二不应该被打印出来,因为它在数组中是不可用的,为了完成这个任务,我不得不使用这么多的if语句,有没有一种方法可以不用这么多的if语句来完成它,谢谢。

h5qlskok

h5qlskok1#

您可能需要这样的内容:

function callDays(days: string[]) {
   const POSSIBLE_DAYS: string[] = ['Sunday','Monday','Wednesday','Thursday','Friday','Saturday'];

   days.forEach((day) => {
      if (POSSIBLE_DAYS.includes(day))
         console.log(`${day} is included`);
   });
}

稍微复杂但可能更快的实现是:

function callDays(days: string[]) {
   const POSSIBLE_DAYS_SET: Set<string> = new Set(['Sunday','Monday','Wednesday','Thursday','Friday','Saturday']);

   days.forEach((day) => {
      if (POSSIBLE_DAYS.has(day))
         console.log(`${day} is included`);
   });
}

编辑:用于调用基于所提供数组中休息日的函数

function sundayActivity() {}
function mondayActivity() {}
function tuesdayActivity() {}
function wednesdayActivity() {}
function thursdayActivity() {}
function fridayActivity() {}
function saturdayActivity() {}

const POSSIBLE_DAYS = {
  sunday: sundayActivity,
  monday: mondayActivity,
  tuesday: tuesdayActivity,
  wednesday: wednesdayActivity,
  thursday: thursdayActivity,
  friday: fridayActivity,
  saturday: saturdayActivity,
} as const

function callDays(days: string[]) {
  days.forEach((day) => {
    if (day.toLowerCase() in POSSIBLE_DAYS) 
      POSSIBLE_DAYS[day.toLowerCase()]()
  })
}

相关问题