0

我正在尝试创建一个 JS 函数,将今天的日期与一组生日进行比较,并在今天是某人的生日时提醒用户。以下是我的代码;

const birthdays = [
  { name: "Bob Marley", birthmonth: "06", birthdate: "01" },
  { name: "Peter Pan", birthmonth: "08", birthdate: "04" },
];

const today = new Date();

if (
  today.getDate() === birthdays.birthdate &&
  today.getMonth() === birthdays.birthmonth
) {
  alert("Happy Birthday!" + birthdays.name);
} else {
  alert("Have a nice day!");
}
4

2 回答 2

1

birtdays 它的任务解决方案数组

const birthdays = [
  { name: "Bob Marley", birthmonth: 5, birthdate: 1 },
  { name: "Peter Pan", birthmonth: 7, birthdate: 4 },
];

const today = new Date();


  birthdays.find((it) => {
    if(it.birthdate === today.getDay() && it.birthmonth === today.getMonth())
    {
      return alert("Happy Birthday!" + it.name)
    } else {
    alert("Have a nice day!");
    }
})

并为您的意见

const newB = birthdays.reduce((acc, rec) => {
  if (rec.birthdate === today.getDay() && rec.birthmonth === today.getMonth()){
    return acc.concat(rec.name)
  } return acc
},[])

if (newB.length > 0){
  alert("Happy Birthday!" + newB)
} else (
  alert("Have a nice day!")
)
于 2020-06-01T06:56:22.407 回答
0

它无法按预期工作的一个原因是您将其存储birthmonth为带有前导零的字符串,而以数字today.getMonth()输出月份,范围为第一个月。同样适用(仅没有范围)。一个工作示例应该是:0-110birthdate

const birthdays = [
  { name: "Bob Marley", birthmonth: 5, birthdate: 1 },
  { name: "Peter Pan", birthmonth: 7, birthdate: 4 },
];

另一个原因是它birthdays是一个数组,你不要这样对待它。

一个可能的修复使用some

if (birthdays.some(date => 
    today.getDate() === date.birthdate 
    && 
    today.getMonth() === date.birthMonth
   )
于 2020-06-01T06:41:29.793 回答