【问题标题】:JS function that compare today date to array of birthdays将今天日期与生日数组进行比较的 JS 函数
【发布时间】:2020-06-01 06:35:05
【问题描述】:

我正在尝试创建一个 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!");
}

【问题讨论】:

  • 问题出在哪里?

标签: javascript


【解决方案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!");
    }
})

对于你的 cmets

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!")
)

【讨论】:

  • 这对我有用,谢谢!为什么我们必须将月份减一而不是日期?
  • 一个整数,介于 0 和 11 之间,根据本地时间表示给定日期中的月份。 0 对应 1 月,1 对应 2 月,依此类推。
  • 如果我有两个生日相同的人,我如何告诉控制台同时打印出两个名字?
【解决方案2】:

它不能按预期工作的一个原因是您将birthmonth 存储为带有前导零的字符串,而today.getMonth()数字 值范围为0-11 其中@ 输出月份987654324@ 是第一个月。 birthdate 也是如此(仅没有范围)。 一个工作示例应该是:

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
   )

【讨论】:

  • 我修复了它,但它仍在打印 else 语句,而不是显示生日快乐消息。
  • 是的,你说得对,还有一个大错误需要解决。敬请期待
猜你喜欢
  • 2020-10-25
  • 1970-01-01
  • 2019-03-12
  • 2022-11-06
  • 1970-01-01
  • 1970-01-01
  • 2012-05-10
  • 2014-11-03
  • 1970-01-01
相关资源
最近更新 更多