DRY:如何将重复的日期代码简化为一个函数?

时间:2019-02-01 08:18:59

标签: javascript

  • 是否可以将其填充到函数或数组中?
  • 如何简化代码?

var yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    yesterday.setHours(03, 0, 0, 0);
    var today = new Date();
    today.setHours(03, 0, 0, 0);
    var tomorrow1 = new Date();
    tomorrow1.setDate(tomorrow1.getDate() + 1);
    tomorrow1.setHours(03, 0, 0, 0);
    var tomorrow2 = new Date();
    tomorrow2.setDate(tomorrow2.getDate() + 2);
    tomorrow2.setHours(03, 0, 0, 0);
    var tomorrow3 = new Date();
    tomorrow3.setDate(tomorrow3.getDate() + 3);
    tomorrow3.setHours(03, 0, 0, 0);

3 个答案:

答案 0 :(得分:4)

您可以将添加小时和日期的重复代码移到函数中,然后将该函数用作map中的参数

const getNthDay = (n) => {
  const day = new Date();
  day.setDate(day.getDate() + n);
  day.setHours(03, 0, 0, 0);
  return day;
}

const arrayOfDates = [-1,0,1,2,3].map(getNthDay);

console.log(arrayOfDates)

答案 1 :(得分:1)

您可以使用map()方法:

const [yesterday, today, tommorow1, tommorow2, tommorow3] = [-1, 0, 1, 2, 3].map(x => {
  const date = new Date();
  date.setDate(date.getDate() + x);
  date.setHours(03, 0, 0, 0);
  return date;
});

console.log(yesterday, today, tommorow1, tommorow2, tommorow3);

答案 2 :(得分:0)

地图和解构。

var [yesterday, today, tomorrow1, tomorrow2, tomorrow3] = [-1, 0, 1, 2, 3].map(offset => {
   var d = new Date();
   d.setDate(d.getDate() + offset);
   d.setHours(03, 0, 0, 0);
   return d;
});

console.log(yesterday);
console.log(today);
console.log(tomorrow1);
console.log(tomorrow2);
console.log(tomorrow3);