Javascript DRY:如何将日期的重复代码简化为函数? 是否可以将其填充到函数或数组中? 如何简化代码?

Javascript DRY:如何将日期的重复代码简化为函数? 是否可以将其填充到函数或数组中? 如何简化代码?,javascript,Javascript,var昨天=新日期(); 昨日.setDate(昨日.getDate()-1); 昨天,设定时间(03,0,0,0); var today=新日期(); 今天,设定时间(03,0,0,0); var tomorrow1=新日期(); tomorrow1.setDate(tomorrow1.getDate()+1); 明天1.设定时间(03,0,0,0); var tomorrow2=新日期(); tomorrow2.setDate(tomorrow2.getDate()+2); 明天2.设定时间

var昨天=新日期();
昨日.setDate(昨日.getDate()-1);
昨天,设定时间(03,0,0,0);
var today=新日期();
今天,设定时间(03,0,0,0);
var tomorrow1=新日期();
tomorrow1.setDate(tomorrow1.getDate()+1);
明天1.设定时间(03,0,0,0);
var tomorrow2=新日期();
tomorrow2.setDate(tomorrow2.getDate()+2);
明天2.设定时间(03,0,0,0);
var tomorrow3=新日期();
tomorrow3.setDate(tomorrow3.getDate()+3);
明天3.设定时间(03,0,0,0)您可以使用
map()
方法:

const[昨天,今天,tommorow1,tommorow2,tommorow3]=[-1,0,1,2,3].map(x=>{
const date=新日期();
date.setDate(date.getDate()+x);
设定时间(03,0,0,0);
返回日期;
});
log(昨天、今天、tommorow1、tommorow2、tommorow3)您可以使用
map()
方法:

const[昨天,今天,tommorow1,tommorow2,tommorow3]=[-1,0,1,2,3].map(x=>{
const date=新日期();
date.setDate(date.getDate()+x);
设定时间(03,0,0,0);
返回日期;
});
log(昨天、今天、tommorow1、tommorow2、tommorow3)映射和分解结构

var[昨天、今天、明天1、明天2、明天3]=[-1、0、1、2、3]。地图(偏移量=>{
var d=新日期();
d、 设置日期(d.getDate()+偏移量);
d、 设定时间(03,0,0,0);
返回d;
});
console.log(昨天);
console.log(今天);
控制台日志(明天1);
控制台日志(明天2);
console.log(明天3)映射和分解结构

var[昨天、今天、明天1、明天2、明天3]=[-1、0、1、2、3]。地图(偏移量=>{
var d=新日期();
d、 设置日期(d.getDate()+偏移量);
d、 设定时间(03,0,0,0);
返回d;
});
console.log(昨天);
console.log(今天);
控制台日志(明天1);
控制台日志(明天2);

console.log(明天3)您可以将添加小时和日期的重复代码移动到函数中,然后将该函数用作中的参数

const getNthDay=(n)=>{
const day=新日期();
day.setDate(day.getDate()+n);
设定时间(03,0,0,0);
回归日;
}
const arrayOfDates=[-1,0,1,2,3].map(getNthDay);

console.log(arrayOfDates)
您可以将添加小时和日期的重复代码移动到函数中,然后将该函数用作

const getNthDay=(n)=>{
const day=新日期();
day.setDate(day.getDate()+n);
设定时间(03,0,0,0);
回归日;
}
const arrayOfDates=[-1,0,1,2,3].map(getNthDay);

console.log(arrayOfDates)
欢迎使用StackOverflow!请,这样其他人可以帮助你。欢迎来到StackOverflow!求你了,这样别人就能帮你了。