日期时间日期前集合函数



嗨,我需要帮助来调整我的日期前函数。它的作用是它为我提供了从向后计数的日期的集合,但我的函数问题是它没有正确显示第 3 个日期,它应该是 17 而不是 16 有人可以看看他们是否知道为什么它会这样

Date.prototype.datesAgo = function(num) {
let date = this;
let arr = [];
for(let i = 0; i < num; i++) {
arr.push(i.toString());
}
let days = arr.slice(0, num).join(' ');
console.log(days)
return days.split(' ').map(function(n) {
date.setDate(date.getDate() - n);
return (function(year, month, day) {
return [year, month < 10 ? '0'+ month : month, day < 10 ? '0' + day : day].join('-');
})(date.getFullYear(), date.getMonth(), date.getDate());
}).join(',');
}
console.log(new Date('2018-05-19').datesAgo(3))

在每次迭代中,您都会改变原始date对象:

date.setDate(date.getDate() - n);

因此,在每次后续迭代中,您都会从上次迭代的date中减去n,而不是原始日期。改为在每次迭代中克隆原始日期对象:

Date.prototype.datesAgo = function(num) {
const date = this;
const dateStrs = Array.from({ length: num }, (_, i) => {
const clonedDate = new Date(date.getTime());
clonedDate.setDate(date.getDate() - i);
return (function(year, month, day) {
return [year, month < 10 ? '0' + month : month, day < 10 ? '0' + day : day].join('-');
})(clonedDate.getFullYear(), clonedDate.getMonth(), clonedDate.getDate());
});
return dateStrs.join(',');
}
console.log(new Date('2018-05-19').datesAgo(3))

最新更新