gpt4 book ai didi

javascript - DateTime dateAgo 集合函数

转载 作者:行者123 更新时间:2023-12-03 01:50:54 25 4
gpt4 key购买 nike

您好,我需要帮助来调整 dateAgo 函数。它的作用是给我一个从向后计数的日期开始的日期集合,但我的函数的问题是它没有正确显示第三个日期,它应该是 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);

因此,在每次后续迭代中,您都会从最后一次迭代日期中减去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))

关于javascript - DateTime dateAgo 集合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50421513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com